本文用到四个类:
Long;//长整形,java用此类型作时间戳 java.text.SimpleDateFormat;//简单时间格式,用作格式输出 String;//字符串 java.util.Date;//时间类,用来获得时间戳等等与时间相关的方法
获得时间戳
Date date=new Date(); long timestamp=date.getTime(); //时间戳
时间戳转换为带格式的字符串
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); //设置格式 String timeText=format.format(timestamp); //获得带格式的字符串
带格式的字符串转换为时间戳
String time="2018-1-9 12:17:22" SimpleDateFormat format=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); //设置要读取的时间字符串格式 Date date = format.parse(time); //转换为Date类 Long timestamp=date.getTime(); //获得时间戳
就是这么简单就可以实现来回转换了~