简体   繁体   English

在Joda DateTime的小数秒内的Unix纪元时间

[英]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. 我有一个以小数秒表示的unix时间戳,我需要将其转换为joda DateTime但我仍然坚持寻找正确的转换格式。 Value looks like this 1403533177.806899 and when I try to parse this I'm getting the following exception 值看起来像1403533177.806899,当我尝试解析这个时,我得到以下异常

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. 使用在线epoch转换器我没有任何问题转换它。 Can anyone suggest me the right conversion string for this timestamp? 任何人都可以建议我为这个时间戳正确的转换字符串?

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. 这将您给定的秒和微秒四舍五入到最接近的毫秒,并基于此创建一个新的DateTime实例。

You have an epoch timestamp in seconds, while the JodaTime DateTime internal representation is also an epoch timestamp in milliseconds. 您有一个以秒为单位的纪元时间戳,而JodaTime DateTime内部表示也是一个以毫秒为单位的纪元时间戳。

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM