在LocalDateTime和Date之间转换

转换LocalDateTimeDate Java示例,反之亦然。

1)日期到LocalDateTime

Java示例,以从转换DateLocalDateTime

Date todayDate = new Date();

LocalDateTime ldt = Instant.ofEpochMilli( todayDate.getTime() )
							.atZone( ZoneId.systemDefault() )
							.toLocalDateTime();

System.out.println(ldt); 	//2018-07-15T11:53:31.863

2)LocalDateTime到日期

Java示例,以从转换LocalDateTimeDate

LocalDateTime localDateTime = LocalDateTime.now();

Date date = Date.from( localDateTime.atZone( ZoneId.systemDefault()).toInstant());

System.out.println(date); 	//Sun Jul 15 11:58:26 IST 2018

DateUtils类

实用程序类,带有在DateLocalDateTime变体之间进行转换的简单方法类。

import java.time.Instant;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.Date;

public class DateUtils {

	public static Date asDate(LocalDate localDate) {
		return Date.from(localDate.atStartOfDay().atZone(ZoneId.systemDefault()).toInstant());
	}

	public static Date asDate(LocalDateTime localDateTime) {
		return Date.from(localDateTime.atZone(ZoneId.systemDefault()).toInstant());
	}

	public static LocalDate asLocalDate(Date date) {
		return Instant.ofEpochMilli(date.getTime()).atZone(ZoneId.systemDefault()).toLocalDate();
	}

	public static LocalDateTime asLocalDateTime(Date date) {
		return Instant.ofEpochMilli(date.getTime()).atZone(ZoneId.systemDefault()).toLocalDateTime();
	}
}

如何使用

import java.time.LocalDateTime;
import java.util.Date;

public class Main 
{
	public static void main(String[] args) 
	{
		Date date = DateUtils.asDate(LocalDateTime.now());

		System.out.println(date);	//Sun Jul 15 12:08:44 IST 2018

		LocalDateTime today = DateUtils.asLocalDateTime(new Date());

		System.out.println(today);	//2018-07-15T12:08:44.492
	}
}

学习愉快!

参考文献:

  1. LocalDateTime Javadoc
  2. ZoneId Javadoc
  3. 日期Javadoc

saigon has written 1440 articles

Leave a Reply