java使用Date格式化输入输出日期
Date格式化输出日期,思路是通过SimpleDateFormat格式化输入和输出
输入代码
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
Date parse = simpleDateFormat.parse("2021-04-12");
long time = parse.getTime();
这里需要抛出ParseException
输入结果
System.out.println(parse);
System.out.println(time);
Mon Apr 12 00:00:00 CST 2021
1618156800000
输出
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
long time = 2618156800000l;
Date day = new Date(time);
String format = simpleDateFormat.format(day);
System.out.println(format);
输出结果
2052-12-19
总结
使用Date可以格式化输入输出日期,从毫秒数上转为格式化的日期,转成字符串,方便操作。
可以提前定义
final static long oneDay = 1000 * 60 * 60 * 24;
作为一天的毫秒数,方便操作。