Java8 LocalDate、Date、LocalDateTime、时间戳的转换

作者: adm 分类: java 发布时间: 2022-10-08

1.LocalDate转Date

LocalDate nowLocalDate = LocalDate.now();
Date date = Date.from(localDate.atStartOfDay(ZoneOffset.ofHours(8)).toInstant());

2.LocalDateTime转Date

LocalDateTime localDateTime = LocalDateTime.now();
Date date = Date.from(localDateTime.atZone(ZoneOffset.ofHours(8)).toInstant());

3.Date转LocalDateTime(LocalDate)

Date date =newDate();
LocalDateTime localDateTime = date.toInstant().atZone(ZoneOffset.ofHours(8)).toLocalDateTime();
LocalDate localDate = date.toInstant().atZone(ZoneOffset.ofHours(8)).toLocalDate();

4.LocalDate转时间戳

LocalDate localDate = LocalDate.now();
longtimestamp = localDate.atStartOfDay(ZoneOffset.ofHours(8)).toInstant().toEpochMilli();

5.LocalDateTime转时间戳

LocalDateTime localDateTime = LocalDateTime.now();
longtimestamp = localDateTime.toInstant(ZoneOffset.ofHours(8)).toEpochMilli();

6.时间戳转LocalDateTime(LocalDate)

longtimestamp = System.currentTimeMillis();
LocalDate localDate = Instant.ofEpochMilli(timestamp).atZone(ZoneOffset.ofHours(8)).toLocalDate();
LocalDateTime localDateTime = Instant.ofEpochMilli(timestamp).atZone(ZoneOffset.ofHours(8)).toLocalDateTime();
public class Test {
 
	//1.LocalDateTime转为"yyyy/MM/dd"
	public static String formatLocalDateTimeString(LocalDateTime date) {
		DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy/MM/dd");
		return date.format(dtf);
	}
 
	//2.LocalDateTime转为"yyyy-MM-dd HH:mm:ss"
	public static String formatLocalDateTimeString1(LocalDateTime date) {
		DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
		return date.format(dtf);
	}
 
	//3.Date转为"yyyy/MM/dd"
	public static String formatDateTimeString(Date date) {
		SimpleDateFormat df = new SimpleDateFormat("yyyy/MM/dd");
		return df.format(date);
	}
 
	//4.Date转为"yyyy-MM-dd HH:mm:ss"
	public static String formatDateTimeString1(Date date) {
		SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		return df.format(date);
	}
 
	public static void main(String[] args) {
		LocalDateTime nowDate = LocalDateTime.now();
		String date1 = formatLocalDateTimeString(nowDate);
		System.out.println("LocalDateTime转为"yyyy/MM/dd"格式=====" + date1);
		String date2 = formatLocalDateTimeString1(nowDate);
		System.out.println("LocalDateTime转为"yyyy-MM-dd HH:mm:ss"格式=====" + date2);
 
		System.out.println();
 
		Date nowDate1 = new Date();
		String date3 = formatDateTimeString(nowDate1);
		System.out.println("Date转为"yyyy/MM/dd"格式=====" + date3);
		String date4 = formatDateTimeString1(nowDate1);
		System.out.println("Date转为"yyyy-MM-dd HH:mm:ss"格式=====" + date4);
 
	}
}

如果觉得我的文章对您有用,请随意赞赏。您的支持将鼓励我继续创作!