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) ?
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() ;
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?
- Java SE 8, Java SE 9, Java SE 10, Java SE 11, and later
- Built-in.
- Part of the standard Java API with a bundled implementation.
- Java 9 adds some minor features and fixes.
- Java SE 6 and Java SE 7
- Much of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport.
- Android
- Later versions of Android bundle implementations of the java.time classes.
- For earlier Android (<26), the ThreeTenABP project adapts ThreeTen-Backport (mentioned above). See How to use ThreeTenABP….
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.