[Java] Date / time operations

Date / time manipulation

Get current time

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.OffsetDateTime;
import java.time.ZonedDateTime;

public class Main {
  //Get the current date and time
  public static void main(String[] args) {
    System.out.println(LocalDateTime.now());  //2020-10-31T07:49:16.502455881
    System.out.println(OffsetDateTime.now()); //2020-10-31T07:49:16.503291965Z
    System.out.println(ZonedDateTime.now());  //020-10-31T07:49:16.504062367Z[Etc/UTC]
    System.out.println(LocalDate.now());      //2020-10-31
    System.out.println(LocalTime.now());      //07:49:16.504349859
  }
}

Get a specific date and time

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.Month;
import java.time.OffsetDateTime;
import java.time.OffsetTime;
import java.time.ZoneId;
import java.time.ZoneOffset;
import java.time.ZonedDateTime;


public class Main {
  //Get a specific date and time
  public static void main(String[] args) {
    //Generate date and time from date / hour / minute / second nanosecond
    var ldt1 = LocalDateTime.of(2019, 1, 10, 10, 20, 30, 513);
    var ldt2 = LocalDateTime.of(2019, Month.JANUARY, 10, 10, 20, 30);
    //var ldt3 = LocalDateTime.of(2019, 1, 40, 10, 20, 30); //Error because it is out of range
    System.out.println(ldt1); //2019-01-10T10:20:30.000000513
    System.out.println(ldt2); //2019-01-10T10:20:30.000000513

    //Generate only date / time
    var ld = LocalDate.of(2019, 1, 10);
    System.out.println(ld);   //2019-01-10
    var lt = LocalTime.of(10, 20, 30);
    System.out.println(lt);  //10:20:30
    var ldt4 = LocalDateTime.of(ld, lt);
    System.out.println(ldt4); //2019-01-10T10:20:30

    //Time zone offset value(ZoneOffset object)
    var odt = OffsetDateTime.of(2019, 1, 10, 10, 20, 30, 999, ZoneOffset.ofHours(9));
    System.out.println(odt); //2019-01-10T10:20:30.000000999+09:00

    var ot = OffsetTime.of(10, 20, 30, 999, ZoneOffset.ofHours(9));
    System.out.println(ot); //10:20:30.000000999+09:00

    var zdt = ZonedDateTime.of(2019, 1, 10, 10, 20, 30, 999, ZoneId.of("Asia/Tokyo"));
    System.out.println(zdt); //2019-01-10T10:20:30.000000999+09:00[Asia/Tokyo]
  }
}

Convert datetime string

import java.time.LocalDate;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;


public class Main {
  //Convert from date / time string
  public static void main(String[] args) {
    //ISO date
    System.out.println(LocalDate.parse(
        "2019-01-01", DateTimeFormatter.ISO_DATE)); //2019-01-01
    //Year and days
    System.out.println(LocalDate.parse(
        "2019-123", DateTimeFormatter.ISO_ORDINAL_DATE)); //2019-05-03
    //Year and number of weeks
    System.out.println(LocalDate.parse(
        "2019-W40-5", DateTimeFormatter.ISO_WEEK_DATE)); //2019-10-04
    //Date and time with time zone ID
    System.out.println(ZonedDateTime.parse(
      "2019-01-10T10:20:30.000000999+09:00[Asia/Tokyo]",
      DateTimeFormatter.ISO_DATE_TIME)); //2019-01-10T10:20:30.000000999+09:00[Asia/Tokyo]
  }
}

Compare date and time

import java.time.LocalDateTime;
public class Main {
  public static void main(String[] args) {
    var dt1 = LocalDateTime.of(2019, 12, 31, 10, 20, 30);
    var dt2 = LocalDateTime.of(2020, 1, 1, 10, 20, 30);
    System.out.println(dt1.equals(dt2));   //false
    System.out.println(dt1.isBefore(dt2)); //true
    System.out.println(dt1.isAfter(dt2));  //false
  }
}

Get time element

import java.time.LocalDateTime;
import java.time.temporal.ChronoField;

public class Main {
  public static void main(String[] args) {
    var dt = LocalDateTime.of(2019, 1, 10, 10, 20, 30, 123);
    var week = new String[] {"Sunday", "Monday", "Tuesday", "Wednesday","Thursday", "Friday", "Saturday"};
    System.out.println(dt.getYear() + "Year" +dt.getMonthValue() + "Moon" +dt.getDayOfMonth() + "Day" +dt.getDayOfWeek() + " " +dt.getHour() + "Time" +dt.getMinute() + "Minutes"+ dt.getSecond() + "Seconds"+ dt.getNano() + "ナノSeconds");
    System.out.println("The month name is" + dt.getMonth() +"this year" + dt.getDayOfYear() + "Day"); //The month name isJANUARYthis year10Day
    //Get time with Chrono Field
    System.out.println(dt.get(ChronoField.YEAR) + "Year" +dt.get(ChronoField.MONTH_OF_YEAR) + "Moon" +dt.get(ChronoField.DAY_OF_MONTH) + "Day" +week[dt.get(ChronoField.DAY_OF_WEEK) -1] + " "+dt.get(ChronoField.HOUR_OF_DAY) + "Time" +dt.get(ChronoField.MINUTE_OF_HOUR) + "Minutes" +dt.get(ChronoField.SECOND_OF_MINUTE) + "Seconds" +dt.get(ChronoField.NANO_OF_SECOND) + "ナノSeconds");
  }
} //Wednesday, January 10, 2019 10:20:30 123 nanoseconds

Format date and time

import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
import java.time.format.FormatStyle;

public class Main {
  public static void main(String[] args) {
    var dt1 = LocalDateTime.of(2020, 11, 1, 10, 20, 30);
    var dt2 = ZonedDateTime.of(2019, 11, 1, 10, 20, 30, 0, ZoneId.of("Asia/Tokyo"));

    System.out.println(dt1.format(DateTimeFormatter.ofLocalizedDate(FormatStyle.FULL)));      //Sunday, November 1, 2020
    System.out.println(dt2.format(DateTimeFormatter.ofLocalizedDateTime(FormatStyle.LONG)));  //November 1, 2019 at 10:20:30 AM JST
    System.out.println(dt1.format(DateTimeFormatter.ofLocalizedDate(FormatStyle.MEDIUM)));    //Nov 1, 2020
    System.out.println(dt2.format(DateTimeFormatter.ofLocalizedDateTime(FormatStyle.SHORT))); //11/1/19, 10:20 AM
  }
}
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;

public class Main {
  public static void main(String[] args) {
    var dt1 = LocalDateTime.of(2020, 11, 1, 10, 20, 30);
    var dt2 = ZonedDateTime.of(2020, 11, 1, 10, 20, 30, 0, ZoneId.of("Asia/Tokyo"));
    System.out.println(dt1.format(DateTimeFormatter.ofPattern("y.MM.dd H:m:s"))); //2020.11.01 10:20:30
    System.out.println(dt2.format(DateTimeFormatter.ofPattern("Y year L month d day (E) a K hour m minute s second(z)"))); //November 1, 2020 (Sun) 10:20:30 AM(JST)
  }
}
//Japanese Calendar
import java.time.chrono.JapaneseDate;
import java.time.chrono.JapaneseEra;
import java.time.format.DateTimeFormatter;

public class Main {
  public static void main(String[] args) {
    var d = JapaneseDate.of(JapaneseEra.REIWA, 2, 1, 1);
    System.out.println(d); //Japanese Reiwa 2-01-01
    //G is the era
    var df = DateTimeFormatter.ofPattern("Gy year MM month dd day");
    System.out.println(d.format(df)); //Reiwa January 01, 2
  }
}

Date-time difference difference

//Days elapsed count
import java.time.Duration;
import java.time.LocalDateTime;
import java.time.Period;

public class Main {
  public static void main(String[] args) {
    var dt1 = LocalDateTime.of(2019, 12, 31, 0, 0, 0);
    var dt2 = LocalDateTime.of(2020, 11, 1, 10, 20, 30);

    var period = Period.between(dt1.toLocalDate(), dt2.toLocalDate());
    System.out.println("Date difference:" +
      period.getYears() + "Year" + period.getMonths() + "months" +
      period.getDays() + "Days"); //日付の差:0年10ヶ月1Days

    var duration = Duration.between(dt1, dt2);
    System.out.println("Time difference:" + duration.toHours() + "time"); //Time difference:7354time
  }
}

Date addition subtraction

//x years later,y days ago
import java.time.LocalDate;
import java.time.temporal.ChronoUnit;
public class Main {
  public static void main(String[] args) {
    var d = LocalDate.of(2020, 11, 1);
    System.out.println(d); //2020-11-01
    //3 years later
    System.out.println(d.plus(3, ChronoUnit.YEARS)); //2023-11-01
    //22 days ago
    System.out.println(d.minus(22, ChronoUnit.DAYS)); //2020-10-10
  }
}
import java.time.Duration;
import java.time.LocalDateTime;
import java.time.Period;
public class Main {
  public static void main(String[] args) {
    var d = LocalDateTime.of(2020, 11, 1, 10, 20, 30);
    var period = Period.ofYears(3);
    //P<date>T<time>
    var duration = Duration.parse("P22DT1H1M1S"); //22 days 1 hour 1 minute 1 second
    System.out.println(d);  //2020-11-01T10:20:30
    System.out.println(d.plus(period)); //2023-11-01T10:20:30
    System.out.println(d.minus(duration)); //2020-10-10T09:19:29
  }
}

Calendar class (Java 7 or earlier)

//Calendar to Date-Convert to Time API
import java.time.LocalDateTime;
import java.time.OffsetDateTime;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.util.Calendar;

public class Main {
  public static void main(String[] args) {
    var cal = Calendar.getInstance();
    var dt1 = LocalDateTime.ofInstant(cal.toInstant(), ZoneId.systemDefault());
    var dt2 = OffsetDateTime.ofInstant(cal.toInstant(), ZoneId.systemDefault());
    var dt3 = ZonedDateTime.ofInstant(cal.toInstant(), ZoneId.systemDefault());
    System.out.println(dt1); //2020-11-01T03:30:12.156
    System.out.println(dt2); //2020-11-01T03:30:12.156Z
    System.out.println(dt3); //2020-11-01T03:30:12.156Z[Etc/UTC]
  }
}
//Date-Convert from Time API to Calender
import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.util.Calendar;
import java.util.Date;

public class Main {
  public static void main(String[] args) {
    var dt = LocalDateTime.of(2020, 11, 1, 10, 20, 30, 123456789);
    var d = Date.from(dt.toInstant(ZoneOffset.of("+09:00")));
    //Enter a value from Date to Calendar with the setTime method
    var cal = Calendar.getInstance();
    cal.setTime(d);
    System.out.println(cal); //java.util.GregorianCalendar[time=1604193630123,,(Abbreviation),,AM_PM=0,HOUR=1,HOUR_OF_DAY=1,MINUTE=20,SECOND=30,MILLISECOND=123,ZONE_OFFSET=0,DST_OFFSET=0]
    }
}

Recommended Posts

[Java] Date / time operations
[MySQL] [java] Receive date and time
Date and time
[Java] How to set the Date time to 00:00:00
Java 8 to start now ~ Date time API ~
Accurate time measurement (Java)
Java basic date manipulation
Date manipulation in Java 8
The date time of java8 has been updated
java: Add date [Note]
[Java] Date type conversion
[Java] Date Related Term Memo
View current date in Java
[Java] Summary of mathematical operations
Handle Java 8 date and time API with Thymeleaf with Spring Boot
What is the LocalDateTime class? [Java beginner] -Date and time class-
Sample code to parse date and time with Java SimpleDateFormat
[Java] Use ResolverStyle.LENIENT to handle the date and time nicely
Java release date and EOL summary
Date processing in Java (LocalDate: Initialization)
Java Unit Test Library-Artery-Current Date Judgment
Handling of time zones using Java
The relationship between strict Java date checking and daylight savings time
[Ruby] Date, Time, Datetime class basics
Java
[Java] Date period duplication check sample
Java
[Java] Processing time measurement method memo
[Java] How to get the current date and time and specify the display format
[Java 8] Function that returns UTC time as Date type (calculated using OffsetZone)
How to implement date calculation in Java
Java date data type conversion (Date, Calendar, String)
Introduction to java for the first time # 2
Studying Java 8 (date API in java.time package)
Convert from java UTC time to JST time
Explanation of Ruby Time and Date objects
[Java] How to measure program execution time
Output Date in Java in ISO 8601 extended format
Compare Android Java dates only (excluding time)
How to get the date in java
Learning for the first time java [Introduction]
java Calendar class (time set, comparison, format)
Oracle Select SQL date parameters take time
[Java] Get the date with the LocalDateTime class
[Java] Get and display the date 10 days later using the Time API added from Java 8.
Parse the date and time string formatted by the C asctime function in Java