常见类型:
java.time.LocalDateTime
java.sql.Timestamp
java.util.Date
以及long类型的毫秒值,
string类型的年月日时分秒
获取当前时间
LocalDateTime: LocalDateTime.now();
Date: new Date();
Timestamp: new Timestamp(传入当前的毫秒值);
获取当前的毫秒值long
System.currentTimeMillis();
new Date().getTime();
Instant.now().toEpochMilli();
Calendar.getInstance().getTimeInMillis();
LocalDateTime.now().toInstant(ZoneOffset.of("+8")).toEpochMilli() //不建议使用,明显比别的几个慢, 如需转成秒,LocalDateTime.now().toEpochSecond(ZoneOffset.of("+8"));
long类型毫秒值转其他
//Timestamp:
new Timestamp(**long**);
//LocalDateTime:
LocalDateTime.ofInstant(Instant.ofEpochMilli(**long**), ZoneOffset.of("+8"));
//Date:
new Date(**long**);
string类型转其他(记得判空), 以 String str=“2022/05/10 10:11:12” 为例
String str="2022/05/10 10:11:12";
//LocalDateTime:
DateTimeFormatter df = DateTimeFormatter.ofPattern("yyyy/MM/dd HH:mm:ss");
LocalDateTime.parse(str,df);
//Timestamp:
不可转 仅限于Timestamp.valueOf("2022-05-10 10:11:12")这一种格式 . 或先转换成其他类型,获取毫秒值再转
//Date:
SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
Date parse = sdf.parse(str);
//String: 打印结果2022-05-10 10-11-12, 发现replaceFirst在源数据为空的情况下会报错,用hutool的方法替换.ReUtil.replaceAll
String s=str.replaceFirst("^(\\d{4})/(\\d{2})/(\\d{2}) (\\d{2}):(\\d{2}):(\\d{2})$"
, "$1-$2-$3 $4-$5-$6");
ReUtil.replaceAll(str, "^(\\d{4})(\\d{2})(\\d{2})$", "$1-$2-$3");
LocalDateTime转其他
LocalDateTime ld= LocalDateTime.now();
//Timestamp:
Timestamp.valueOf(ld);
//Date: 未发现一步到位的方式,可通过其他格式中转
Date date = Date.from(localDateTime.atZone(ZoneId.systemDefault()).toInstant());
或
Date date = Date.from(localDateTime.atOffset(ZoneOffset.of("+8")).toInstant());
//String:
DateTimeFormatter df = DateTimeFormatter.ofPattern("yyyy/MM/dd HH:mm:ss");
String s=df.format(ld);
//毫秒long: 需中转
ld.toInstant(ZoneOffset.of("+8")).toEpochMilli();
或
Timestamp.valueOf(ld).getTime();
Timestamp转其他
Timestamp tt = new Timestamp(1652235928189L);
//LocalDateTime:
tt.toLocalDateTime();
//Date:
new Date(tt.getTime());
//String:
new SimpleDateFormat("yyyy/MM/dd HH/mm/ss").format(tt);
//long:
tt.getTime();
Date转其他
Date dt = new Date();
//LocalDateTime:
dt.toInstant().atZone(ZoneId.systemDefault()).toLocalDateTime();
或
dt.toInstant().atOffset(ZoneOffset.of("+8")).toLocalDateTime();
//Timestamp:
new Timestamp(dt.getTime());
//String:
SimpleDateFormat sf = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
String str=sf.format(dt);
//long:
dt.getTime();
拓展:
LocalDateTime:
//获取当天0点和 23:59:59
LocalDateTime.of(LocalDate.now(), LocalTime.MIN);
LocalDateTime.of(LocalDate.now(), LocalTime.MAX);
todo:
获取当天0点.
时间大小对比api