java SimpleDateFormat日期与时间戳的相互转换

时间:2022-11-30 21:05:14

自我总结,有什么不到位的地方,各位可以帮忙纠正补充一下,感激不尽!

目的:SimpleDateFormat类可以很随意的组合日期时间的格式,不止单纯的yyyy-MM-dd这种格式

废话不多说,上代码

测试类 DateTest

package com.core.test;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date; public class DateTest { public static void main(String[] args) throws ParseException {
SimpleDateFormat sdf0 = new SimpleDateFormat("yyyyMMdd");
SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd");
SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy年MM月dd日");
SimpleDateFormat sdf3 = new SimpleDateFormat("ddMMyyyy"); String time0 = "20140916";
String time1 = "2014-09-16";
String time2 = "2014年09月16日";
String time3 = "16092014"; convertStamp(sdf0, time0);
convertStamp(sdf1, time1);
convertStamp(sdf2, time2);
convertStamp(sdf3, time3); long stamp = 1410796800000L;
convertDate(sdf0, stamp);
convertDate(sdf1, stamp);
convertDate(sdf2, stamp);
convertDate(sdf3, stamp);
} // 日期转换成时间戳
public static void convertStamp(SimpleDateFormat format, String time)throws ParseException {
Date date = format.parse(time);
System.out.println(date.getTime());
} // 时间戳转换成日期
public static void convertDate(SimpleDateFormat sdf, long stamp) {
String date = sdf.format(new Date(stamp));
System.out.println(date);
} }

运行结果:

1410796800000
1410796800000
1410796800000
1410796800000
20140916
2014-09-16
2014年09月16日
16092014

SimpleDateFormat很灵活吧,哈哈