Java – How is custom epoch time calculated? Not UNIX era

How is custom epoch time calculated? Not UNIX era… here is a solution to the problem.

How is custom epoch time calculated? Not UNIX era

I’m receiving data from the server in seconds and I want to convert it to the latest data.

But the seconds I received are not since UNIX epoch 01/01/1970, but 01/01/2000.

Usually I would use:

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

where millisConvert is the number of seconds I received to convert to milliseconds. But now, naturally, I get the wrong date because the source is different. How do I change the epoch (origin)?

Solution

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 modern java.time classes to replace the dreaded old legacy classes such as Date and Calendar.

Immediate

AnInstant represents a moment in UTC.

Define your specific era reference datetime.

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

Add your seconds.

Instant later = epoch.plusSeconds( yourSecondsGoHere ) ; 

Offset datetime

If you want a pure date value with no time and time zone, use the LocalDate class. First, convert the base type Instant to a more flexible OffsetDateTime, specifying the constant ZoneOffset.UTC as the offset.

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

Local date

Extract date-only values.

LocalDate ld = odt.toLocalDate() ;

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


About java.time

placed in Java 8 and later within the java.time framework. These classes replace the troublesome old classes legacy datetime classes, eg java.util.Date , Calendar , & SimpleDateFormat .

<a href=”http://www.joda.org/joda-time/” rel=”noreferrer noopener nofollow”>Joda-Time project, now in Maintenance mode, it is recommended to migrate to the java.time class .

To learn more, see >Oracle Tutorial Search for many examples and explanations. The specification is JSR 310

You can exchange java.time objects directly with your database. Use JDBC driver conform JDBC 4.2 or later. No strings, no java.sql.* classes.

Where do I get the java.time class?

enter image description here

ThreeTen-Extra project extends java.time with additional classes. The project is a testing ground for future things that might be added to java.time. You may find some useful classes here, such as Interval , YearWeek , YearQuarter , and more .

Related Problems and Solutions