Use of Date Type in Java

Asked 1 years ago, Updated 1 years ago, 60 views

I would like to know how to generate a Date class instance with the information "January 1, 2016 0:0:0:00:00 ms" and then display the elapsed time in milliseconds since January 1, 1970 00:00:00 GMT.

I don't know how to make the time zone JST and how to specify milliseconds.

java

2022-09-30 21:43

2 Answers

Regarding Date type instance generation, it is deprecated to set a specific date to Date and instantiate it, so we will instantiate it once in the Calendar class and then convert it to Date type.
Also, I will specify Timezone at the same time.

Calendar cal=Calendar.getInstance();
TimeZone jst = TimeZone.getTimeZone("JST");
cal.set (2016, 1, 1, 0, 0, 0);
cal.setTimeZone(jst);
Date = cal.getTime();

Milliseconds can be obtained using the getTime method in the Date class.

 long ms = date.getTime();


2022-09-30 21:43

Java 8 or later recommends that you use the new date/time type and convert it as needed to older models such as java.util.Date.

If you follow the questionnaire:

// January 1, 2016
// Supplement: The last argument is nanoseconds, not milliseconds.
finalLocalDateTime = LocalDateTime.of (2016, 1, 1, 0, 0, 0);
System.out.println("datetime:"+time);

// "Japan Time" January 1, 2016
// Supplement: Short Zone IDs such as "JST" are not recommended (see JavaDoc)
// // https://docs.oracle.com/javase/jp/11/docs/api/java.base/java/time/ZoneId.html#SHORT_IDS
finalZoneId jst = ZoneId.of("JST", ZoneId.SHORT_IDS);
finalZonedDateTime jstTime =ZonedDateTime.of(time,jst);
System.out.println("datetime(JST):"+jstTime);

finalOffsetDateTimebaseTime=OffsetDateTime.of(1970,1,1,0,0,0,ZoneOffset.UTC);
System.out.println("base:"+baseTime);

final long millis = ChronoUnit.MILLIS.between (baseTime, jstTime);
System.out.println("diff:"+millis);

// Conversion from Java 8 Dae&Time Type to Java.util.Date Type
final Date jstDate=Date.from(jstTime.toInstant());
System.out.println("date:"+jstDate);

This is what it looks like without redundancy:

//2016-01-01T00:00+09:00
final ZoneOffset offset=ZoneOffset.ofHours(9);
final OffsetDateTime JapaneseTime = OffsetDateTime.of (2016, 1, 1, 0, 0, 0, offset);
System.out.println("time(+9:00):"+JapaneseTime);

// I don't want to take any point in time difference, I just want to get epoch seconds, so I don't need to calculate.
final long millis=JapaneseTime.toInstant().toEpochMilli();
System.out.println("diff:"+millis);

// Conversion from Java 8 Dae&Time Type to Java.util.Date Type
final Date = Date.from (JapaneseTime.toInstant());
System.out.println("date:"+date);


2022-09-30 21:43

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.