I'm trying to use JODA to simply convert a numeric timestamp (a long
representing Unix epoch time), to a Month Day, Year
string.
Here's code I just ran a few seconds ago:
long lTimestamp = 1315600867; // Current timestamp is approx 9/9/11 3:41 PM EST
DateTime oTimestamp = new DateTime(lTimestamp);
String strMon, strDay, strYear;
strMon = oTimestamp.monthOfYear().getAsText(Locale.ENGLISH);
strDay = oTimestamp.dayOfMonth().getAsText(Locale.ENGLISH);
开发者_Go百科 strYear = oTimestamp.year().getAsText(Locale.ENGLISH);
String strDate = strMon + " " + strDay + ", " + strYear;
System.out.println("Converted timestamp is : " + strDate);
The output to this is January 16, 1970!!!
Does this make any sense to anyone?!?!
The long
you pass into the DateTime
constructor is meant to be in milliseconds, not seconds - so use 1315600867000L instead and it's all fine.
Documentation states:
Constructs an instance set to the milliseconds from 1970-01-01T00:00:00Z using ISOChronology in the default time zone.
If you're getting a value which is already in seconds, you just need to multiply by 1000:
long timestampInSeconds = getValueFromDatabase();
long timestampInMillis = timestampInSeconds * 1000L;
DateTime dt = new DateTime(timestampInMillis);
I'd actually advise you to use Instant
in this case rather than DateTime
- you don't really have a time zone to consider. If you are going to use DateTime
, you should specify the time zone explicitly, e.g.
DateTime dt = new DateTime(timestampInMillis, DateTimeZone.UTC);
精彩评论