Skip to content

Instantly share code, notes, and snippets.

@sthum
Last active June 17, 2016 08:21
Show Gist options
  • Save sthum/a30cafa0f03a5ef3e95193d181b6ce9e to your computer and use it in GitHub Desktop.
Save sthum/a30cafa0f03a5ef3e95193d181b6ce9e to your computer and use it in GitHub Desktop.
Util class to convert between Java 8 DateTime API and the old java.util.Date class
import java.time.Instant;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.ZoneId;
import java.util.Date;
/**
* Converts between the new Java 8 DateTime API and the old (not-so-beloved) {@link java.util.Date} class.
* The conversions use the system default locale timezone , otherwise the time will change.
*/
public class Java8DateTimeConverter {
/**
* Convert from Date to LocalDateTime
*
* @param date the {@link Date} to convert
*
* @return LocalDateTime at {@link ZoneId#systemDefault()}
*/
public static LocalDateTime DateToLocalDateTime(Date date) {
Instant instant = Instant.ofEpochMilli(date.getTime());
return LocalDateTime.ofInstant(instant, ZoneId.systemDefault());
}
/**
* Convert from Date to LocalDateTime
*
* @param date the {@link Date} to convert
*
* @return LocalDate at {@link ZoneId#systemDefault()}
*/
public static LocalDate DateToLocalDate(Date date) {
Instant instant = Instant.ofEpochMilli(date.getTime());
return LocalDateTime.ofInstant(instant, ZoneId.systemDefault()).toLocalDate();
}
/**
* Convert from Date to LocalDateTime
*
* @param time the {@link Date} to convert
*
* @return LocalTime at {@link ZoneId#systemDefault()}
*/
public static LocalTime DateToLocalTime(Date time) {
Instant instant = Instant.ofEpochMilli(time.getTime());
return LocalDateTime.ofInstant(instant, ZoneId.systemDefault()).toLocalTime();
}
/**
* Convert from LocalDateTime to Date
*
* @param ldt the {@link LocalDateTime} to convert
*
* @return Date at {@link ZoneId#systemDefault()}
*/
public static Date LocalDateTimeToDate(LocalDateTime ldt) {
Instant instant = ldt.atZone(ZoneId.systemDefault()).toInstant();
return Date.from(instant);
}
/**
* Convert from LocalDate to Date
*
* @param ld the {@link LocalDate} to convert
*
* @return Date at {@link ZoneId#systemDefault()} whereas the time of the date is at start of the day
*/
public static Date LocalDateToDate(LocalDate ld) {
Instant instant = ld.atStartOfDay().atZone(ZoneId.systemDefault()).toInstant();
return Date.from(instant);
}
/**
* Convert from LocalTime to Date
*
* @param lt the {@link LocalTime} to convert
*
* @return Date at {@link ZoneId#systemDefault()} on todays date
*/
public static Date LocalTimeToDate(LocalTime lt) {
LocalDate now = LocalDate.now();
Instant instant = lt.atDate(now).atZone(ZoneId.systemDefault()).toInstant();
return Date.from(instant);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment