DateTimeFormatter 时间戳和String类型日期
2020-07-08 本文已影响0人
楼兰King
代码如下:
import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;
public class ceshi {
public static void main(String[] args) {
String num="2020-05-29 14:06:51.577";
long zhi=strTimestamp(num);
System.out.println("string转为时间戳:"+zhi);
String a=timeToStr(zhi);
System.out.println("时间戳转为string:"+a);
}
public static long strTimestamp(String str) {
long time;
String pattern="yyyy-MM-dd HH:mm:ss.SSS";
DateTimeFormatter formatter = DateTimeFormatter.ofPattern(pattern);
LocalDateTime localDateTime=LocalDateTime.parse(str,formatter);
time=localDateTime.toInstant(ZoneOffset.ofHours(12)).toEpochMilli();
return time;
}
public static String timeToStr(long num) {
String time="";
String pattern="yyyy-MM-dd HH:mm:ss.SSS";
LocalDateTime dateTime = LocalDateTime.ofEpochSecond(num/1000L, 0, ZoneOffset.ofHours(12));
time = dateTime.format(DateTimeFormatter.ofPattern(pattern));
return time;
}
}
输出结果:
string转为时间戳:1590718011577
时间戳转为string:2020-05-29 14:06:51.000
如需按8小时制,修改12为8即可。