Java中的一些格式转换

概述

本文整理了JDK中一些常用的格式转换,方便忘记时查询使用。(本文将不定期更新)

时间

在线时间转换校验工具https://www.sojson.com/unixtime.html

String装换为Date
 //字符串转时间
 String time = "2020-04-01 12:00:00";
 SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
 Date date = simpleDateFormat.parse(time);
Date转换为String

结合①中示例使用

 //时间转换为字符串
String format = simpleDateFormat.format(date);
Date转换为时间戳Long
 //时间转为为时间戳
long timeStamp = date.getTime();

日历

☆通过日历格式获取时间参数的的标准值

  String[] WEEKS={"星期日","星期一","星期二","星期三","星期四","星期五","星期六"};
  Calendar calendar = Calendar.getInstance();
  calendar.setTimeInMillis(timeParam);

  String dayOfWeek = WEEKS[calendar.get(Calendar.DAY_OF_WEEK) - 1];
  DecimalFormat decimalFormat=new DecimalFormat("00");
  String hourOfDay=  decimalFormat.format(calendar.get(Calendar.HOUR_OF_DAY));//01 02 ... 24

数字

格式化数字
//数字格式转换
String number = "928";
DecimalFormat decimalFormat = new DecimalFormat("000");
Number parse = decimalFormat.parse(number);
int finalNum = parse.intValue();
发布了42 篇原创文章 · 获赞 6 · 访问量 1743

猜你喜欢

转载自blog.csdn.net/ASYMUXUE/article/details/105238115
今日推荐