String-Date conversion with nanoseconds

后端 未结 4 1528
无人共我
无人共我 2020-11-30 07:50

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 an

4条回答
  •  星月不相逢
    2020-11-30 08:25

    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).

提交回复
热议问题