The date time of java8 has been updated

Date time class before JDK 1.8

Date It is a date / time class provided by jdk1.0 and holds milliseconds from the epoch. "GMT January 1, 1970 00:00 to the present millisecond" Most of the methods are deprecated (@Deprecated) due to Y2k and performance issues.

Surviving contractors and methods


//Generate
Date d1 = new Date();
Date d2 = new Date(System.currentTimeMillis() + 1);

// before,after
System.out.println(d1.after(d2));
System.out.println(d1.before(d2));

// set,get
d1.setTime(System.currentTimeMillis() + 1);
d2.setTime(System.currentTimeMillis() - 1);
System.out.println(d1.getTime());
System.out.println(d2.getTime());

Date y2k problem

y2k problem


System.out.println(new Date(10, 1, 1));

⇒ It will be January 1, 1910.

Date.java


public Date(int year, int month, int date, int hrs, int min, int sec) {
   int y = year + 1900; // <-here
   //Abbreviation
}

Calendar A class that improves the defect of Date.java and represents a calendar as the name suggests.

  1. The Calendar class has fields for year, month, day, hour, minute, second, and milliseconds. protected int fields[];

  2. An abstract class, implemented with the __ (probably) __Tmeplate Method pattern, By implementing subclasses, the differences in calendars used around the world are absorbed. Example: Japanese calendar, lunar calendar

Calendar core API

API Overview
Calendar Of the calendar(abstract)Parent class
TimeZone Represents the time zone
Locale Represents a region and produces different Calendars

Calendar generation

For display


private static void show(Calendar cal) {
    System.out.println("Generated calendar: " + cal.getClass().getName());
    System.out.println(
        cal.get(Calendar.YEAR) + "Year"
        + (cal.get(Calendar.MONTH) + 1) + "Month"
        + cal.get(Calendar.DAY_OF_MONTH) + "Day"
        + cal.get(Calendar.HOUR_OF_DAY) + "Time"
        + cal.get(Calendar.MINUTE) + "Minutes"
        + cal.get(Calendar.SECOND) + "Seconds");
}

Generate


Calendar Default calendar= Calendar.getInstance();
show(Default calendar);

Calendar Japanese calendar_Default time zone= Calendar.getInstance(new Locale("ja", "JP", "JP"));
show(Japanese Calendar_Default time zone);

Calendar default region_JST = Calendar.getInstance(TimeZone.getTimeZone("JST"));
show(Default region_JST);

Calendar Japanese calendar_GMT = Calendar.getInstance(TimeZone.getTimeZone("GMT"), new Locale("ja", "JP", "JP"));
show(Japanese Calendar_GMT);

output


Generated calendar: java.util.GregorianCalendar
November 13, 2017 12:20:00
Generated calendar: java.util.JapaneseImperialCalendar
November 13, 2017 12:20:00
Generated calendar: java.util.GregorianCalendar
November 13, 2017 12:20:00
Generated calendar: java.util.JapaneseImperialCalendar
November 13, 2017 3:20:00
  1. GregorianCalendar, generated in default region
  2. JapaneseImperialCalendar, generated by making the region Japan Japanese-Calendar.PNG

Calendar <=> Date

Calendar,Date conversion


// Date to Calendar
Calendar.getInstance().setTime(new Date());
// Calendar to Date
Calendar.getInstance().getTime();

Difference between add () and roll ()

Both add () and roll () are for increasing / decreasing the specified field (year / month / day / hour / minute / second / millisecond).

Top Lower
add() Change the top Minimal change
roll() Do not change the top Minimal change

add()


Calendar calendar = Calendar.getInstance();
calendar.set(2015, Calendar.NOVEMBER,  30);
System.out.println("initial value: " + formatter.format(calendar.getTime()));

calendar.add(Calendar.MONTH, 3);
System.out.println("add : " + formatter.format(calendar.getTime()));

__2015 / 11/30-> add month +3-> 2016/2/29 __

roll()


Calendar calendar = Calendar.getInstance();
calendar.set(2015, Calendar.NOVEMBER,  30);
System.out.println("initial value: " + formatter.format(calendar.getTime()));

calendar.roll(Calendar.MONTH, 3);
System.out.println("roll : " + formatter.format(calendar.getTime()));

__2015 / 11/30-> roll month +3-> 2015/2/28 __

Lenient & Delay

python


SimpleDateFormat formatter = new SimpleDateFormat("yyyy/MM/dd");
Calendar calendar = Calendar.getInstance();
calendar.set(2015, 15,  32);
System.out.println(formatter.format(calendar.getTime()));  // 2016/05/02

calendar.setLenient(false);
calendar.set(2015, 15,  32);
// Exception in thread "main" java.lang.IllegalArgumentException: MONTH
System.out.println(formatter.format(calendar.getTime()));

output


2016/05/02
Exception in thread "main" java.lang.IllegalArgumentException: MONTH
  1. Lenient's default is true, so allow 2015/15/32-> 2016/05/02
  2. Lenient = falase doesn't allow month = 15
  3. __ The exception is raised by get () instead of set. __ __set () is delayed to prevent unnecessary calculations. __

JDK 1.8 datetime class

__ The main subject! !! __ Many date and time classes have been added to the java.time package since JKD 1.8.

Core API jdk8-datetime-class (1).png

Core API

Date time core API Overview
TemporalAccessor To date, time, offset, or any combination of them, etc.Read-onlyAn interface that defines access.
Temporal To date, time, offset, or any combination of them, etc.Read/writeAn interface that defines access.
TemporalAmount __Amount of time__The interface that defines.
TemporalField __Date time__Interface that defines the fields of.
TemporalUnit __Date time unit__Functional interface that defines.
TemporalAdjuster __Date time adjustment strategy__Functional interface for providing.
TemporalQuery __Strategy to access date and time__Functional interface for providing.

TemporalAccessor

TemporalAccessor method result
TemporalAccessor temporalAccessor = LocalDate.of(2016, 2, 9) 2016-02-09
temporalAccessor.get(ChronoField.YEAR) 2016
temporalAccessor.getLong(ChronoField.MONTH_OF_YEAR) 2
temporalAccessor.isSupported(ChronoField.HOUR_OF_DAY) false
temporalAccessor.range(ChronoField.DAY_OF_MONTH) 1 - 29
temporalAccessor.query(TemporalQueries.precision()) Days
  1. Get the instance with LocalDate that implements TemporalAccessor.
  2. Get the year field using it in the ChronoField that implements TemporalField.
  3. TemporalQuery implementation Use the returned TemporalQueries.zoneId () to get the precision.

Temporal Temporal inherits from TemporalAccessor and adds a write interface.

Temporal method result
Temporal temporal = LocalDate.of(2016, 10, 1) 2016-10-01
temporal.plus(10, ChronoUnit.MONTHS) 2017-08-01
temporal.minus(Period.ofYears(1)) 2015-10-01
temporal.minus(2, ChronoUnit.YEARS) 2014-10-01
temporal.with(ChronoField.YEAR, 2010) 2010-10-01
temporal.with(LocalDate.of(2010, 1, 10)) 2010-01-10
temporal.until(LocalDate.of(2016, 1, 1), ChronoUnit.DAYS) -274
  1. Addition and subtraction with Period that implements Temporal Amount.
  2. Addition and subtraction with ChronoUnit which implements TemporalUnit.
  3. Adjust the year field with the ChronoField that implements TemporalField.
  4. LocalDate.of (2010, 1, 10) in temporal.with (LocalDate.of (2010, 1, 10)) is cast to Temporal Adjuster.

TemporalAmount

TemporalAmount method result
TemporalAmount temporalAmount = Duration.ofDays(61) P61D
temporalAmount.getUnits() [Years, Months, Days]
temporalAmount.get(ChronoUnit.DAYS) 61
temporalAmount.get(ChronoUnit.MONTHS) 0
temporalAmount.subtractFrom(LocalDate.of(2010, 10, 1)) 2010-08-01
temporalAmount.addTo(LocalDate.of(2010, 10, 1)) 2010-12-01
  1. Get a instance with Duration that implements Temporal Amount.
  2. Get the value with ChronoUnit which implements TemporalUnit.

TemporalField

TemporalField method result
TemporalField year = ChronoField.YEAR Year
year.range() -999999999 - 999999999
year.getBaseUnit() Years
year.getDisplayName(Locale.JAPAN) Year
year.getFrom(LocalDate.of(2011, 1, 10)) 2011
year.getRangeUnit() Forever
year.isDateBased() true
year.isTimeBased() false

I'm getting an instance with ChronoField which implements TemporalField.

TemporalUnit

TemporalUnit method result
TemporalUnit days = ChronoUnit.DAYS Days
days.addTo(LocalDate.of(2011, 1, 1), 2) 2011-01-03
days.getDuration() PT24H
days.isSupportedBy(LocalDate.now()) true
days.isDurationEstimated() true
days.isDateBased() true
days.isTimeBased() false

TemporalAdjuster&TemporalAdjusters

TemporalAdjuster method result
TemporalAdjuster adjuster = LocalDate.of(2011, 1, 1) 2011-01-01
adjuster.adjustInto(LocalDate.of(9999, 10, 1)) 2011-01-01

Temporal Adjusters offers a variety of time adjustment strategies.

TemporalAdjusters result
LocalDate.of(2011, 1, 1).with(TemporalAdjusters.lastDayOfYear()) 2011-12-31
LocalDate.of(2011, 1, 1).with(TemporalAdjusters.lastDayOfMonth()) 2011-01-31

TemporalQuery, TemporalQueries

Example: How many days are left until the end of the year?

python


TemporalQuery<Long> leftDays = temporal -> {
    LocalDate dayOfTarget = LocalDate.from(temporal);
    LocalDate lastDayOfYear = dayOfTarget.with(TemporalAdjusters.lastDayOfYear());
    Period period = dayOfTarget.until(lastDayOfYear);
    return ChronoUnit.DAYS.between(dayOfTarget, lastDayOfYear);
};
System.out.println(
    LocalDate.of(2015, 10, 3).query(leftDays)
);

Temporal Queries offers a variety of access strategies. Example: What is the precision of the object?

LocalDate.of(2015, 10, 3).query(TemporalQueries.precision())

Date time implementation

Instant

  1. __Invariant & Threadsafe __ class that represents epoch seconds (time elapsed from 1970-01-01T 00:00:00 Z).
  2. Hold up to nanoseconds.
  3. It inherits Temporal and TemporalAdjuster.
Instance acquisition toString()
Instant.now() 2017-11-14T01:47:25.392Z
Instant.now(Clock.systemUTC()) 2017-11-14T01:47:25.486Z
Instant.now(Clock.system(ZoneId.of("Asia/Shanghai"))) 2017-11-14T01:47:25.502Z
Instant.parse("2016-10-10T10:20:30.123Z") 2016-10-10T10:20:30.123Z
Instant.EPOCH 1970-01-01T00:00:00Z
Instant.ofEpochMilli(10) 1970-01-01T00:00:00.010Z
Instant.ofEpochSecond(1) 1970-01-01T00:00:01Z
Instant.ofEpochSecond(1, 2) 1970-01-01T00:00:01.000000002Z
Regular method result
Instant instant = Instant.parse("2016-10-10T10:00:00.000Z") 2016-10-10T10:00:00Z
instant.toEpochMilli() 1476093600000
instant.plusSeconds(30) 2016-10-10T10:00:30Z
instant.minusSeconds(30) 2016-10-10T09:59:30Z
instant.isAfter(instant) false
instant.isBefore(instant) false
instant.equals(instant) true

LocalDate __ No timezone An immutable & thread safe class that represents a date __ (yyyy-mm-dd). It can be used for birthdays.

Instance acquisition toString()
LocalDate.now() 2017-11-14
LocalDate.now(Clock.systemUTC()) 2017-11-14
LocalDate.now(ZoneId.of("Europe/Paris")) 2017-11-14
LocalDate.of(2015, 10, 1) 2015-10-01
LocalDate.parse("2015 - 10 - 10") 2015-10-10
LocalDate.ofYearDay(2016, 60) 2016-02-29
Regular method toString()
LocalDate.of(2010, 2, 3).getYear() 2010
LocalDate.of(2010, 2, 3).getMonth() FEBRUARY
LocalDate.of(2010, 2, 3).getDayOfMonth() 3
LocalDate.of(2010, 3, 3).getDayOfWeek() WEDNESDAY
LocalDate.of(2010,1,1).withMonth(3).withYear(2016).withDayOfMonth(15) 2016-03-15
LocalDate.of(2010,1,1).withYear(2016).withDayOfYear(59) 2016-02-28
LocalDate.of(2010,1,1).minusYears(1).minusMonths(2).minusDays(3) 2008-10-29
LocalDate.of(2010,1,1).plusYears(1).plusMonths(2).plusDays(3) 2011-03-04

LocalTime __ An immutable & thread-safe class that represents no timezone __ (HH: mm: ss.SSSSSSSSS).

Instance acquisition toString()
LocalTime.now() 12:06:40.790
LocalTime.now(Clock.systemUTC()) 03:06:40.805
LocalTime.now(ZoneId.of("Europe/Paris")) 04:06:40.868
LocalTime.of(6, 10, 30) 06:10:30
LocalTime.parse("10:20:30") 10:20:30
LocalTime.of(6, 10, 30, 999999999) 06:10:30.999999999
Regular method toString()
LocalTime.of(10, 20, 30).getHour() 10
LocalTime.of(10, 20, 30).getSecond() 30
LocalTime.of(10, 20, 30).getMinute() 20
LocalTime.of(10, 20, 30).withHour(11).withMinute(22).withSecond(33).withNano(44) 11:22:33.000000044
LocalTime.of(10, 20, 30).minusHours(1).minusMinutes(1).minusSeconds(1).minusNanos(1) 09:19:28.999999999
LocalTime.of(10, 20, 30).plusHours(1).plusMinutes(1).plusSeconds(1).plusNanos(1) 11:21:31.000000001

LocalDateTime It has LocalDate and LocalTime internally, __ No time zone Date Time __ (yyyy-mm-dd HH: mm: ss.SSSSSSSSS) is an immutable & thread-safe class.

LocalDataTime.java


/**
 * The date part.
 */
private final LocalDate date;
/**
 * The time part.
 */
private final LocalTime time;
Instance acquisition toString()
LocalDate.now() 2017-11-14T12:45:41.756
LocalDate.now(Clock.systemUTC()) 2017-11-14T03:45:41.756
LocalDate.now(ZoneId.of("Europe/Paris")) 2017-11-14T04:45:41.834
LocalDateTime.of(2010, 10, 1, 10, 20, 30, 123456789) 2010-10-01T10:20:30.123456789
ZonedDateTime.parse("2010-10-01T10:20:30.123456789") 2010-10-01T10:20:30.123456789
Regular method toString()
LocalDateTime.of(2010, 10, 1, 10, 20, 30).getYear() 2010
LocalDateTime.of(2010, 10, 1, 10, 20, 30).getMonth() OCTOBER
LocalDateTime.of(2010, 10, 1, 10, 20, 30).getDayOfMonth() 1
LocalDateTime.of(2010, 10, 1, 10, 20, 30).getDayOfYear() 274
LocalDateTime.of(2010, 10, 1, 10, 20, 30).getHour() 10
LocalDateTime.of(2010, 10, 1, 10, 20, 30).getMinute() 20
LocalDateTime.of(2010, 10, 1, 10, 20, 30).getSecond() 30
LocalDateTime.of(2010, 10, 1, 10, 20, 30).plusYears(1) 2011-10-01T10:20:30
LocalDateTime.of(2010, 10, 1, 10, 20, 30).minusYears(1) 2009-10-01T10:20:30

ZoneDateTime An immutable & thread-safe class that represents __ (HH: mm: ss.SSSSSSSSS) with a timezone. The basic usage seems to be the same as LocalTimeDate.

Instance acquisition toString()
ZonedDateTime.now() 2017-11-14T12:53:12.536+09:00[Asia/Tokyo]
ZonedDateTime.now(Clock.systemUTC()) 2017-11-14T03:53:12.536Z
ZonedDateTime.now(ZoneId.of("Europe/Paris")) 2017-11-14T04:53:12.598+01:00[Europe/Paris]
ZonedDateTime.of(LocalDateTime.now(), ZoneId.of("Asia/Shanghai")) 2017-11-14T12:53:12.614+08:00[Asia/Shanghai]
ZonedDateTime.of(2010, 10, 1, 10, 20,30, 999, ZoneId.of("Asia/Tokyo")) 2010-10-01T10:20:30.000000999+09:00[Asia/Tokyo]
ZonedDateTime.parse("2010-10-01T10:20:30.000000999+09:00[Asia/Tokyo]") 2010-10-01T10:20:30.000000999+09:00[Asia/Tokyo]
Regular method toString()
ZonedDateTime.of(2010, 10, 1, 10, 20, 30, 999, ZoneId.of("Asia/Tokyo")).getYear() 2010
ZonedDateTime.of(2010, 10, 1, 10, 20, 30, 999, ZoneId.of("Asia/Tokyo")).getMonth() OCTOBER
ZonedDateTime.of(2010, 10, 1, 10, 20, 30, 999, ZoneId.of("Asia/Tokyo")).getDayOfMonth() 1
ZonedDateTime.of(2010, 10, 1, 10, 20, 30, 999, ZoneId.of("Asia/Tokyo")).getDayOfYear() 274
ZonedDateTime.of(2010, 10, 1, 10, 20, 30, 999, ZoneId.of("Asia/Tokyo")).getHour() 10
ZonedDateTime.of(2010, 10, 1, 10, 20, 30, 999, ZoneId.of("Asia/Tokyo")).getMinute() 20
ZonedDateTime.of(2010, 10, 1, 10, 20, 30, 999, ZoneId.of("Asia/Tokyo")).getSecond() 30
ZonedDateTime.of(2010, 10, 1, 10, 20, 30, 999, ZoneId.of("Asia/Tokyo")).plusYears(1) 2011-10-01T10:20:30.000000999+09:00[Asia/Tokyo]
ZonedDateTime.of(2010, 10, 1, 10, 20, 30, 999, ZoneId.of("Asia/Tokyo")).minusYears(1) 2009-10-01T10:20:30.000000999+09:00[Asia/Tokyo]

OffsetDateTime It is a combination of LocalDateTime and Offset.

https://docs.oracle.com/javase/jp/8/docs/api/java/time/OffsetDateTime.html "OffsetDateTime, ZonedDateTime, and Instant all store instants in time series to nanosecond precision. Instant is the simplest and simply represents instant. OffsetDateTime adds the offset from UTC / Greenwich to the instant. And allow you to get the local date / time. ZonedDateTime adds a complete time zone rule. "

OffsetDateTime.java


/**
 * The local date-time.
 */
private final LocalDateTime dateTime;
/**
 * The offset from UTC/Greenwich.
 */
private final ZoneOffset offset;

YearMonth、MonthDay

YearMonth: An immutable & thread-safe class that represents yyyy-mm. MonthDay: An immutable & thread-safe class that represents mm-dd.

Get YearMonth instance toString()
YearMonth.now() 2017-11
YearMonth.now(Clock.systemUTC()) 2017-11
YearMonth.now(ZoneId.of("Europe/Paris")) 2017-11
YearMonth.of(2011, 10) 2011-10
YearMonth.parse("2012-10") 2012-10
YearMonth regular method toString()
YearMonth.of(2011, 10).getYear() 2011
YearMonth.of(2011, 10).getMonth() OCTOBER
YearMonth.of(2011, 10).plusMonths(2) 2011-12
YearMonth.of(2011, 10).minusYears(3) 2008-10
Get MonthDay instance toString()
MonthDay.now() --11-14
MonthDay.now(Clock.systemUTC()) --11-14
MonthDay.now(ZoneId.of("Europe/Paris")) --11-14
MonthDay.of(5, 10) --05-10
MonthDay.parse("--05-10") --05-10
MonthDay regular method toString()
MonthDay.of(5, 10).getMonth() MAY
MonthDay.of(5, 10).getDayOfMonth() 10
MonthDay.of(5, 10).with(Month.JANUARY).withDayOfMonth(20) --01-20

Year Year: An immutable & thread-safe class that represents yyyy.

Instance acquisition toString()
Year.now() 2017
Year.now(Clock.systemUTC()) 2017
Year.now(ZoneId.of("Europe/Paris")) 2017
Year.of(2011) 2011
Year.parse("2012") 2012
Regular method toString()
Year.of(2011).getValue() 2011
Year.of(2011).plusYears(3) 2014
Year.of(2011).minusYears(10) 2001

Month、DayOfWeek Month, an enumeration that represents the month DayOfWeek, an enumeration representing the days of the week

Get Month Instance toString()
Month.of(10) OCTOBER
Month.valueOf("JANUARY") JANUARY
Month.FEBRUARY FEBRUARY
Month regular method toString()
Month.of(1).getValue() 1
Month.of(12).plus(3) MARCH
Month.of(3).minus(4) NOVEMBER
Get DayOfWeek instance toString()
DayOfWeek.of(1) MONDAY
DayOfWeek.valueOf("FRIDAY") FRIDAY
DayOfWeek.FRIDAY FRIDAY
DayOfWeek regular method toString()
DayOfWeek.of(1).getValue() 1
DayOfWeek.of(1).plus(7) MONDAY
DayOfWeek.of(1).minus(7) MONDAY

Clock __ A class that represents the system time __ with a time zone. The date / time class now () is generated based on this Clock.

Get Clock

Clock clockDefault = Clock.systemDefaultZone();  

defalut-clock-1.gif

UTC clock


Clock clockUTC = Clock.systemUTC();  

UTC-Clock2.gif

Time zone designation clock


Clock clockParis= Clock.system(ZoneId.of("Europe/Paris"));

clock-paris.gif

Clock is a clock, so time advances

Time advances


Clock clock = Clock.systemDefaultZone();
System.out.println(clock.instant());
Thread.sleep(1000 * 2);
System.out.println(clock.instant());
2017-11-13T11:41:27.548Z
2017-11-13T11:41:29.551Z

Get a special watch

Clock that is stopped


Clock fixedClock = Clock.fixed(Instant.now(), ZoneId.of("Asia/Tokyo"));
System.out.println("fixed clock : " + fixedClock.instant());
Thread.sleep(1000 * 2);
System.out.println("fixed clock : " + fixedClock.instant());

result


fixed clock : 2017-11-13T11:46:01.224Z
fixed clock : 2017-11-13T11:46:01.224Z

__⇒ The clock does not advance. __

Second clock


Clock secondsTickClock = Clock.tickSeconds(ZoneId.of("Asia/Tokyo"));
System.out.println("seconds tick clock : " + secondsTickClock.instant());
Thread.sleep(1000 * 2);
System.out.println("seconds tick clock : " + secondsTickClock.instant());

result


seconds tick clock : 2017-11-13T11:52:20Z
seconds tick clock : 2017-11-13T11:52:22Z

__ ⇒ In seconds, do not hold less than seconds __

Minute clock


Clock minutesTickClock = Clock.tickMinutes(ZoneId.of("Asia/Tokyo"));
System.out.println("minutes tick clock : " + minutesTickClock.instant());
Thread.sleep(1000 * 2);
System.out.println("minutes tick clock : " + minutesTickClock.instant());

result


minutes tick clock : 2017-11-13T11:52:00Z
minutes tick clock : 2017-11-13T11:52:00Z

__ ⇒ Minutes, do not hold less than seconds __

Clock advanced by the specified time


Clock nowClock = Clock.systemDefaultZone();
Clock offsetClock = Clock.offset(nowClock, Duration.ofDays(1));
System.out.println("nowClock : " + nowClock.instant());
System.out.println("offsetClock : " + offsetClock.instant());

result


nowClock : 2017-11-13T11:58:25.647Z
offsetClock : 2017-11-14T11:58:25.647Z

__⇒ Clock one day ahead __

TemporalAmount Duration An immutable & thread-safe class that expresses the amount of time.

Instance acquisition result
Duration.ofDays(2) PT48H
Duration.ofHours(3) PT3H
Duration.ofMinutes(40) PT40M
Duration.parse("PT15M") PT15M
Regular method result
Duration.ofDays(3).getUnits() [Seconds, Nanos]
Duration.ofDays(3).toHours() 72
Duration.ofDays(3).toMinutes() 4320
DDuration.ofDays(3).toMillis() 259200000
Duration.ofDays(3).plusDays(1) PT96H
Duration.ofDays(3).plusDays(-1) PT48H

Period An immutable & thread-safe class that expresses the amount of time.

Instance acquisition result
Period.ofDays(2) P2D
Period.ofMonths(3) P3M
Period.ofYears(4) P4Y
Period.parse("P4Y") P4Y
Regular method result
Period.ofYears(3).getDays() 0
Period.ofYears(3).getMonths() 0
Period.ofYears(3).getYears() 3
Period.ofYears(3).getUnits() [Years, Months, Days]
Period.ofDays(3).plusDays(1) P4D
Period.ofDays(3).minusDays(1) P2D

ZoneId Class that expresses the time zone

python


ZoneId.systemDefault();
ZoneId.getAvailableZoneIds();
ZoneId.of("Asia/Tokyo");

Conversion between datetime classes

Conversion method Converted class
MonthDay.of(10, 1).atYear(2015) java.time.LocalDate
YearMonth.of(2015, 10).atDay(30) java.time.LocalDate
YearMonth.of(2015, 10).atEndOfMonth() java.time.LocalDate
LocalTime.now().atDate(LocalDate.now()) 2017-11-14T14:41:28.728
LocalDate.now().atTime(10, 20) java.time.LocalDateTime
LocalDate.now().atStartOfDay() java.time.LocalDateTime
LocalDate.now().atStartOfDay(ZoneId.of("Asia/Shanghai")) java.time.ZonedDateTime
LocalDateTime.now().atZone(ZoneId.of("Asia/Shanghai")) java.time.ZonedDateTime
LocalDateTime.now().toLocalDate() java.time.LocalDate
LocalDateTime.now().toLocalTime() java.time.LocalTime
LocalDateTime.now().toInstant(ZoneOffset.UTC) java.time.Instant
ZonedDateTime.now().toLocalDateTime() java.time.LocalDateTime
ZonedDateTime.now().toLocalDate() java.time.LocalDate
ZonedDateTime.now().toInstant() java.time.Instant
Instant.now().atZone(ZoneId.of("Asia/Shanghai")) java.time.ZonedDateTime
Instant.now().atOffset(ZoneOffset.UTC) java.time.OffsetDateTime

Date time format

DateFormat It is provided by jdk1.0 ??, and the format is controlled by the following two elements.

  1. LONG,FULL,MEDIUM.SHORT
  2. Locale

Won't you use it anymore? !!

Instance generation & format&parse toString()
DateFormat.getDateInstance(DateFormat.FULL, Locale.JAPAN).format(new Date()) November 14, 2017
DateFormat.getTimeInstance(DateFormat.FULL, Locale.US).format(new Date()) 4:56:05 PM JST
DateFormat.getDateTimeInstance(DateFormat.MEDIUM, DateFormat.SHORT, Locale.CHINA).format(new Date()) 2017-11-14 noon 4:56
DateFormat.getDateInstance(DateFormat.FULL, Locale.JAPAN).parse("November 14, 2017") Tue Nov 14 00:00:00 JST 2017
DateFormat.getTimeInstance(DateFormat.FULL, Locale.US).parse("4:52:25 PM JST") Thu Jan 01 16:52:25 JST 1970
DateFormat.getDateTimeInstance(DateFormat.MEDIUM, DateFormat.SHORT, Locale.CHINA).parse("2017-11-14 noon 4:52") Tue Nov 14 16:52:00 JST 2017

SimpleDateFormat It's a familiar date formatter! !! A subclass of DateFormmat that determines the format with a pattern string.

Instance generation & format&parse toString()
new SimpleDateFormat("yyyy-MM-dd").format(new Date()) 2017-11-14
new SimpleDateFormat("yyyy year MM month dd HH hour mm minute ss second").format(new Date()) November 14, 2017 17:24:11
new SimpleDateFormat("yyyy-MM-dd").parse("2017-11-14") Tue Nov 14 00:00:00 JST 2017

You can set the time zone


SimpleDateFormat s1 = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
SimpleDateFormat s2 = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
s2.setTimeZone(TimeZone.getTimeZone("Asia/Shanghai"));
System.out.println(s1.format(new Date()));
System.out.println(s2.format(new Date()));

output


2017/11/14 17:26:53
2017/11/14 16:26:53

DateTimeFormatter It was added from JKD1.8 along with the datetime class. It's in the java.time.format package and is like a combination of DateFormat and SimpleDateFormat?

format


DateTimeFormatter[] formatters = {
    DateTimeFormatter.ISO_DATE,
    DateTimeFormatter.ISO_LOCAL_DATE,
    DateTimeFormatter.ISO_LOCAL_DATE_TIME,
    DateTimeFormatter.ofLocalizedDateTime(FormatStyle.FULL, FormatStyle.MEDIUM),
    DateTimeFormatter.ofPattern("Gyyyy/MM/dd HH::mm:ss.SSS")
};
LocalDateTime localDateTime = LocalDateTime.now();
Arrays.stream(formatters)
    .forEach(
        formatter ->
            System.out.println(formatter.format(localDateTime))
    );
Arrays.stream(formatters)
    .forEach(
        formatter ->
            System.out.println(localDateTime.format(formatter))
    );

parse


 //Date Time#parse
 LocalDate.parse("2015/10/10", DateTimeFormatter.ofPattern("yyyy/MM/dd"));

 // DateTimeFormatter#parse
 DateTimeFormatter.ofPattern("yyyy/MM/dd").parse("2015/10/10");
 DateTimeFormatter.ofPattern("yyyy/MM/dd").parse("2015/10/10", TemporalQueries.localDate());

From a readability standpoint, datetime #parse is recommended.

Recommended Posts

The date time of java8 has been updated
[Java] How to set the Date time to 00:00:00
What are the updated features of java 13
[Java] Date / time operations
Feel the passage of time even in Java
I translated the grammar of R and Java [Updated from time to time]
Speed comparison at the time of generation at the time of date conversion
What is the LocalDateTime class? [Java beginner] -Date and time class-
[Rails 6] The save timing of active_strage images has been changed.
[Java] Use ResolverStyle.LENIENT to handle the date and time nicely
[Java] Delete the elements of List
[Java version] The story of serialization
Handling of time zones using Java
The origin of Java lambda expressions
[Java1.8 +] Get the date of the next x day of the week with LocalDate
The design concept of Java's Date and Time API is interesting
The relationship between strict Java date checking and daylight savings time
Get the result of POST in Java
Check the contents of the Java certificate store
Examine the memory usage of Java elements
Introduction to java for the first time # 2
[Java] Get the day of the specific day of the week
Memo: [Java] Check the contents of the directory
[Java] How to get the current date and time and specify the display format
Explanation of Ruby Time and Date objects
Compare the elements of an array (Java)
[day: 5] I summarized the basics of Java
Java 8 to start now ~ Date time API ~
This and that of the implementation of date judgment within the period in Java
Easily measure the size of Java Objects
Looking back on the basics of Java
How to get the date in java
Output of the book "Introduction to Java"
Learning for the first time java [Introduction]
[Socket communication (Java)] Impressions of implementing Socket communication in practice for the first time
The story of writing Java in Emacs
The JacocoReportBase.setClassDirectories (FileCollection) method has been deprecated.
[Java] Check the number of occurrences of characters
[Java] [Spring] Test the behavior of the logger
[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.
[Java] Calculate the day of the week from the date (Calendar class is not used)
Parse the date and time string formatted by the C asctime function in Java
Format the date and time given by created_at
[Java] Handling of JavaBeans in the method chain
The story of making ordinary Othello in Java
[Android] [Java] Manage the state of CheckBox of ListView
About the idea of anonymous classes in Java
The order of Java method modifiers is fixed
About date / time type of Doma2 entity class
[Java] Set the time from the browser with jsoup
Measure the size of a folder in Java
[Java] Get the length of the surrogate pair string
[Java] The confusing part of String and StringBuilder
[Note] Java: Measures the speed of string concatenation
Set the time of LocalDateTime to a specific time
[Java] Be careful of the key type of Map
Calculate the similarity score of strings with JAVA
[Java / Kotlin] Resize considering the orientation of the image
I touched on the new features of Java 15
Use Java external library for the time being