Unexpected difference in dates parsed using yyyy-MM-dd hh:mm:ss format

后端 未结 2 1969
太阳男子
太阳男子 2021-01-18 01:09

I\'ve run the below java code to get time difference.

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.         


        
相关标签:
2条回答
  • 2021-01-18 01:26

    This is the problem:

    new SimpleDateFormat("yyyy-MM-dd hh:mm:ss")
    

    The hh here means "12 hour hour-of-day" so 12 means midnight unless there's something to indicate that it's meant to be 12 PM. Your value of 13 only works because the parser is in a lenient mode. You want:

    new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")
    

    I'd also strongly advise you to use Joda Time for this task anyway, as it makes it a lot simpler.

    0 讨论(0)
  • 2021-01-18 01:42

    Changing the SimpleDateFormat pattern to yyyy-MM-dd HH:mm:ss fixes the issues.

    This happens because in the yyyy-MM-dd hh:mm:ss case, 12 is evaluated as 0.

    0 讨论(0)
提交回复
热议问题