How do I make calculation on a custom Epoch time? Not the UNIX epoch

bengongon97 :

I am receiving data from a server in seconds and I want to convert it to date.

But the seconds I am receiving is not since the UNIX epoch 01/01/1970 but is 01/01/2000.

Normally I'd use:

SimpleDateFormat formatter = new SimpleDateFormat("dd/MM/yyyy", Locale.US);
String dateString = formatter.format(new Date(millisToConvert));

Where millisConvert is converted-to-milliseconds seconds that I receive. But now, naturally, I get wrong dates since the origin is different. How do I change the epoch (the origin) ?

Basil Bourque :

tl;dr

OffsetDateTime.of( 2000 , 1 , 1 , 0 , 0 , 0 , 0 , ZoneOffset.UTC )  // Define your epoch reference moment. 
.pluSeconds( yourSeconds )  // Add the number of seconds given to you. Returns another `OffsetDateTime` object rather than altering the original (immutable objects pattern).  
.toLocalDate()     // Extract a date-only value without time-of-day and without offset-from-UTC. 

java.time

Use the modern java.time classes that supplanted the terrible old legacy classes such as Date & Calendar.

Instant

An Instant represents a moment in UTC.

Define your particular epoch reference date-time.

Instant epoch = Instant.parse( "2000-01-01T00:00Z" ) ;

Add your number of seconds.

Instant later = epoch.plusSeconds( yourSecondsGoHere ) ; 

OffsetDateTime

If you want a date-only value without time-of-day and without time zone, use LocalDate class. First, convert from the basic type Instant to the more flexible OffsetDateTime, specifying the constant ZoneOffset.UTC as the offset.

OffsetDateTime odt = instant.atOffset( ZoneOffset.UTC ) ;

LocalDate

Extract the date-only value.

LocalDate ld = odt.toLocalDate() ;

Table of date-time types in Java, both modern and legacy


About java.time

The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.

The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.

To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.

You may exchange java.time objects directly with your database. Use a JDBC driver compliant with JDBC 4.2 or later. No need for strings, no need for java.sql.* classes.

Where to obtain the java.time classes?

enter image description here

The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=79459&siteId=1