1、时间戳转化为Date(or String)
//时间戳转化为Sting或Date
SimpleDateFormat format = new SimpleDateFormat( "yyyy-MM-dd HH:mm:ss" );
Long time=new Long(445555555);
String d = format.format(time);
Date date=format.parse(d);
System.out.println("Format To String(Date):"+d);
System.out.println("Format To Date:"+date);
运行结果:
Format To String(Date):1970-01-06 11:45:55
Format To Date:Tue Jan 06 11:45:55 CST 1970
2、Date(or String)转化为时间戳
//Date或者String转化为时间戳
SimpleDateFormat format = new SimpleDateFormat( "yyyy-MM-dd HH:mm:ss" );
String time="1970-01-06 11:45:55";
Date date = format.parse(time);
System.out.print("Format To times:"+date.getTime());
运行结果:
Format To times:445555000
3、注意
定义SimpleDateFormat时new SimpleDateFormat("yyyy-MM-dd HH:mm:ss" );里面字符串头尾不能有空格,有空格那是用转换时对应的时间空格也要有空格(两者是对应的),比如:
//Date或者String转化为时间戳
SimpleDateFormat format = new SimpleDateFormat( " yyyy-MM-dd HH:mm:ss " );
String time="1970-01-06 11:45:55";
Date date = format.parse(time);
System.out.print("Format To times:"+date.getTime());
运行结果(报错):
Exception in thread "main" java.text.ParseException: Unparseable date: "1970-01-06 11:45:55"
改正:
//Date或者String转化为时间戳
SimpleDateFormat format = new SimpleDateFormat( " yyyy-MM-dd HH:mm:ss " );
String time=" 1970-01-06 11:45:55 ";//注:改正后这里前后也加了空格
Date date = format.parse(time);
System.out.print("Format To times:"+date.getTime());
运行结果:
Format To times:445555000