在工作中碰到过需要和底层交互,使用时间戳进行判断的情况,记录一下时间转换方法
- 自定义时间格式
private static String format = "yyyy-MM-dd HH:mm:ss";
private static SimpleDateFormat sdf = new SimpleDateFormat(format);
- 时间格式化
public static Date parse(String dateStr) {
Date date = new Date();
try {
date = sdf.parse(dateStr);
} catch (ParseException e) {
e.printStackTrace();
}
return date;
}
- 时间戳转为date
public static String CurrentTimeMillis2Date(Long microsecond) {
return sdf.format(new Date(microsecond));
}
- date转为时间戳
public static Long getTimestamp(String time, String type) {
Date date = parse(time);
switch (type) {
case "s":
return date.getTime() / 1000;
case "ms":
return date.getTime();
case "us":
return date.getTime() * 1000;
case "ns":
return date.getTime() * 1000000;
default:
return date.getTime();
}
}
所导入的包:
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;