Java: Date/Time

Commonly used date/time classes

Methods to create an instance

  • .now(); // current date/time
  • .of(3, Month.MARCH, 2012); // specific date / time
  • .of(myLocalDate, myLocalTime); // forming dateTime from date and time object
  • .parse(“2017-12-03T10:20:30”); // parse from string

Methods to obtain elements

  • .getYear()
  • .getMonth(); // Month Enum
  • .getMonthValue(); // 1 to 12
  • .getDayOfMonth();
  • .getDayOfWeek();
  • .getDayOfYear();
  • .getHour()
  • .getMinute()
  • .getSecond()
  • .getNano()

Methods for comparison / calculations

  • .isBefore()
  • .isAfter()
  • .isEqual()
  • .minusYears/Months/Days/Hours/Minutes/Seconds/Nanos
  • .plusYears/Months/Days/Hours/Minutes/Seconds/Nanos

Time Zones

Time zones managed using ZoneIds

ZoneId.systemDefault();
ZoneId.getAvailableZoneIds()
ZoneId.of(myZoneString); // Europe/London, America/Chicago

Util.Date

The older java.util.Date is still available for use.

Date myDate = new Date(); // current time
Date myDate = new Date(myEpochMillis); // specific time

myDate.toInstant();
myDate.after(myDate2);
myDate.before(myDate2);