Frage

I'm trying to set the time to epoch date time in java. how can I do this? so that I could get year months days etc out of the epoch date time.

War es hilfreich?

Lösung

use new Date(0L);

SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd-HH:mm:ss");
sdf.setTimeZone(TimeZone.getTimeZone("UTC"));
System.out.println(sdf.format(new Date(0L)));

Take care of your timezone cause it will change depends on what you have by default.

UPDATE In java 8 you can use the new java.time library

You have this constant Instant.EPOCH

Andere Tipps

As I understand, you only want to store it in some variable? So use Date epoch = new Date(0);

try this

    Calendar c = new GregorianCalendar(TimeZone.getTimeZone("GMT"));
    c.setTimeInMillis(0);
    int day = c.get(Calendar.DATE);
    int month = c.get(Calendar.MONTH) + 1;
    int year = c.get(Calendar.YEAR);

tl;dr

Instant.EPOCH

Using java.time

The troublesome old date-time classes including Date and Calendar are now legacy, supplanted by the java.time classes. Much of the java.time functionality is back-ported to Android (see below).

To get the date-only value of the Java & Unix epoch reference date of 1970-01-01, use LocalDate. The LocalDate class represents a date-only value without time-of-day and without time zone.

LocalDate epoch = LocalDate.ofEpochDay( 0L ) ;

epoch.toString: 1970-01-01

To get the date-time value of that same epoch, use the constant Instant.EPOCH. The Instant class represents a moment on the timeline in UTC with a resolution of nanoseconds (up to nine (9) digits of a decimal fraction).

Instant epoch = Instant.EPOCH ;

epoch.toString(): 1970-01-01T00:00:00Z

The Z in that standard ISO 8601 output is short for Zulu and means UTC.

To get a number of years, months, days since then, use the Period class.

Period period = Period.between( 
     LocalDate.ofEpochDay( 0 ) , 
     LocalDate.now( ZoneId.of( "America/Montreal" ) ) 
) ;

Search Stack Overflow for more discussion and examples of Period.


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.

Where to obtain the java.time classes?

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top