SuperString
SuperString

Reputation: 22549

Want only date from epoch

Given millis since epoch, I want an instance with the fields Month, Date, Year filled out, with the hour minute seconds set to some default values.

What is an efficient way to do this?

I know that there are sql ways to do it but is there a way to do it in Java?

Upvotes: 0

Views: 243

Answers (3)

duffymo
duffymo

Reputation: 309018

Or, if you'd rather not have a JODA dependency, use DateFormat:

Date thisDate = new SimpleDateFormat("yyyy-MMM-dd").parse("2011-Jun-29");

Per the javadocs, you can easily create a Date from a long:

long value = System.currentTimeMillis();
Date thisDate = new Date(value);

Upvotes: 0

L. Cornelius Dol
L. Cornelius Dol

Reputation: 64065

Just use:

new Calendar(new Date(msSinceEpoch));

where the ms is a long value.

Upvotes: 3

jtoberon
jtoberon

Reputation: 9036

Use either LocalDate or DateMidnight in the Joda-Time API. The differences are explained in the javadocs.

Note that in order to truncate a point in time (some millis since epoch) to a specific calendar day, you might want to specify when midnight happened, or else you'll end up with midnight in the system's timezone. For example, you might call the LocalDate(long, DateTimeZone) constructor instead of the LocalDate(long) constructor.

Upvotes: 1

Related Questions