import java.time.Instant;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;
import java.util.Date;
public class DateUtils {
public static void main(String[] args) {
//LocalDateTime转时间戳
// 获取秒数
long l = LocalDateTime.now().toEpochSecond(ZoneOffset.of("+8"));
System.out.println(l);
// 获取毫秒数
long l1 = LocalDateTime.now().toInstant(ZoneOffset.ofHours(+8)).toEpochMilli();
System.out.println(l1);
// 时间戳转LocalDateTime
//1640878737155
LocalDateTime localDateTime = LocalDateTime.ofInstant(Instant.ofEpochMilli(1640878737155L), ZoneOffset.of("+8"));
System.out.println(localDateTime.toString());
//LocalDateTime 转String
DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern(FORMAT_ONE);
String now = LocalDateTime.now().format(dateTimeFormatter);
System.out.println(now);
// String 转LocalDateTime
LocalDateTime string2LocalDateTime = LocalDateTime.parse("2020-12-12 12:12:12", dateTimeFormatter);
System.out.println(string2LocalDateTime);
// LocalDateTime转Date
Date date = new Date(LocalDateTime.now().toInstant(ZoneOffset.ofHours(+8)).toEpochMilli());;
System.out.println(date);
//Date 转LocalDateTime
LocalDateTime localDateTime1 = new Date().toInstant().atOffset(ZoneOffset.of("+8")).toLocalDateTime();
LocalDateTime localDateTime2 = LocalDateTime.ofInstant(new Date().toInstant(), ZoneOffset.of("+8"));
System.out.println(localDateTime1);
System.out.println(localDateTime2);
}
}
LocalDateTime、Date、String和时间戳Long互相转换
最新推荐文章于 2024-07-19 10:51:19 发布