java中日期转化为纳秒,String-Date转换为纳秒

I've been struggling for a while with this piece of code for an Android app and I can't get the hang of it. I've read and tried every solution I found on stackoverflow and other places, but still no luck.

What I want to do is have a function to convert a string like "17.08.2012 05:35:19:7600000" to a UTC date and a function that takes an UTC date and converts it to a string like that.

String value = "17.08.2012 05:35:19:7600000";

DateFormat df = new SimpleDateFormat("dd.MM.yyyy HH:mm:ss:SSSSSSS");

try

{

Date today = df.parse(value);

System.out.println("Today = " + df.format(today) + " " + today.toGMTString());

}

catch (ParseException e)

{

e.printStackTrace();

}

This results in : Today = 17.08.2012 07:41:59:0000000 17 Aug 2012 04:41:59 GMT which are both wrong.

I tried setting SDF's timezone to UTC, no luck.

Another thing that I noticed: if I do df.setLenient(false);

It gives me : java.text.ParseException: Unparseable date: "17.08.2012 05:35:19:7600000" .

If anyone can provide me with some explanations / sample code, I would be very grateful. Thanks in advance

解决方案

The result you are getting is absolutely right.

Let's analyze this:

17.08.2012 05:35:19:7600000

17: Day of month (17th)

08: Month of year (August)

2012: Year (2012)

05: Hour of day (5am)

35: Minute of hour (:35)

19: Second of minute (:19)

7600000: Milliseconds of second (7,600,000)

Now, the way the VM sees this is that you are declaring the time of day as 5:35:19am, then adding 7,600,000 milliseconds to it. 7,600,000 milliseconds = 7,600 seconds = 2 hours, 6 minutes, 40 seconds. 5:35:19am + 02:06:40 = 7:41:59am (and 0 milliseconds). This is the result you are getting. (It also appears that you are not setting the timezone properly, so the GMT string is 3 hours behind your result.)

If you want to retain the :7600000, to my knowledge this is not possible. As this can be simplified into seconds, the VM will automatically reduce it into the other time increments. The milliseconds (the SSSS) should be for storing values <1000.

I'd suggest you create a new SimpleDateFormat for your output; but remember that the milliseconds will be absorbed into the other times (since they are all stored as a single long in the Date object).

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值