not logged in | [Login]

Working with Java Date and DateTime

Time constants

Instead of:

int waitTime = 5 * 60 * 1000; // 5 mins

One can do:

int waitTime = TimeUnit.MINUTES.toMillis(5);

Which JDK 8 date object should I use?

See https://docs.oracle.com/javase/tutorial/datetime/iso/timezones.html

  • ZonedDateTimehandles a date and time with a corresponding time zone with a time zone offset from Greenwich/UTC.
  • OffsetDateTime handles a date and time with a corresponding time zone offset from Greenwich/UTC, without a time zone ID.
  • LocalDateTimeA date-time without a time-zone in the ISO-8601 calendar system, such as 2007-12-03T10:15:30.

Time conversions

Java 8

If you are on JDK 8, you can use the DateTimeFormatter

Parse an ISO 8601 date time from a string

DateTimeFormatter format = DateTimeFormatter.ISO_DATE_TIME;
LocalDateTime date = LocalDateTime.parse("2015-06-24T03:19:46.911Z", format);

Formatting a java.time.LocalDateTime to a string

DateTimeFormatter formatter = DateTimeFormatter.ofPattern("EEEE MMMM dd, yyyy H:mm a");
String s = date.format(formatter);

Formatting a java.time.LocalDateTime to an ISO 8601 string

String s = DateTimeFormatter.ISO_DATE_TIME.format(datetime);

Convert a java.util.Date to a java.time.LocalDateTime

LocalDateTime ldt = LocalDateTime.ofInstant(plainOldDate.toInstant(), ZoneId.of("UTC"));

Convert a java.time.LocalDateTime to a java.util.Date

Date out = Date.from(ldt.atZone(ZoneId.of("UTC")).toInstant());

Convert a org.joda.time.DateTime to a java.time.LocalDateTime

org.joda.time.DateTime jodaDateTime = DateTime.now();
java.time.LocalDateTime java8Ldt = java.time.LocalDateTime.ofInstant(jodaDateTime.toDate().toInstant(), ZoneId.of("UTC"));

That's nasty. Do you know a better way?

JDK <= 7 (JodaTime)

For JDK < 7, use JodaTime

Parse an ISO 8601 Date Time From a String

DateTimeFormatter parser = ISODateTimeFormat.dateTimeParser();
DateTime date = parser.parseDateTime("2013-08-12T19:20:30.045Z");

Formatting a DateTime to a string

DateTimeFormatter fmt = DateTimeFormat.forPattern("MMM dd yyyy 'at' HH:mm:ss z");
String s = fmt.print(new DateTime());

See also:

Time zones

  • Seattle: DateTimeZone.forID("America/Los_Angeles");

Parsing

  • Natty - Natty is a natural language date parser written in Java. Very powerful, look at the example tests.
  • PrettyTime - Human time parsing library for Java
  • jchronic - A port of Ruby's Chronic library