Niranjan Subramanian
Niranjan Subramanian

Reputation: 591

Unix epoch time in fractional seconds to Joda DateTime

I have a unix timestamp that is expressed in fractional seconds, I need to convert this into a joda DateTime but I'm stuck with finding a right conversion format. Value looks like this 1403533177.806899 and when I try to parse this I'm getting the following exception

java.lang.IllegalArgumentException: Invalid format: "1403533177.806899" is malformed at "7.806899"

This is the piece of code I'm using

DateTimeFormatter dtf = DateTimeFormat.forPattern(format);
dtf.parseDateTime(value);

I used the following conversion formats

yyyyMMddHHmmss
yyyy-MM-dd HH:mm:ss.SSS

Using online epoch converter I don't have any problem converting this. Can anyone suggest me the right conversion string for this timestamp?

Upvotes: 2

Views: 7038

Answers (1)

Zoltán
Zoltán

Reputation: 22196

I suggest you don't use date formatter for this, but some simple arithmetic instead:

long millis = Math.round(value * 1000);
DateTime dt = new DateTime(millis, DateTimeZone.forOffsetHours(0));

This rounds your given seconds and microseconds to the nearest millisecond and creates a new DateTime instance based on that.

You have an epoch timestamp in seconds, while the JodaTime DateTime internal representation is also an epoch timestamp in milliseconds.

The formatter converts a human-readable date and time into an epoch, so it's really not what you need, it would just be a long way around.

If you need to print the value later, you can then use a DateTimeFormatter:

DateTimeFormatter dtf = DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss.SSSz");
dtf.print(dt);

Upvotes: 3

Related Questions