使用yyyy-MM-dd hh:mm:ss格式解析日期的意外差异

RVG*_*RVG 8 java simpledateformat

我运行下面的java代码来获得时差.

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


public class Test 
{
    public static SimpleDateFormat simpleDateFormat= new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
    public static Date date1,date2;
    public static long diff; 
    public static String TAG ="DateConversion";
    public static Calendar cal1,cal2;

    public static void main(String a[])
    {
        checkTimeDifference("2013-10-30 10:15:00", "2013-10-30 11:15:00");
        checkTimeDifference("2013-10-30 10:15:00", "2013-10-30 12:15:00");
        checkTimeDifference("2013-10-30 10:15:00", "2013-10-30 13:15:00");
    }

    public static  void checkTimeDifference(String strDate,String checkDate)
    {
        try 
        {
            simpleDateFormat.setTimeZone(TimeZone.getTimeZone("GMT"));
            date1    = simpleDateFormat.parse(strDate);
            date2    = simpleDateFormat.parse(checkDate);

            //in milliseconds
            diff = date2.getTime() - date1.getTime();
            System.out.println("Difference : "+diff);
            long diffSeconds = diff / 1000 % 60;
            long diffMinutes = diff / (60 * 1000) % 60;
            long diffHours = diff / (60 * 60 * 1000) % 24;
            long diffDays = diff / (24 * 60 * 60 * 1000);
            System.out.println(diffDays     + " days, ");
            System.out.println(diffHours    + " hours, ");
            System.out.println(diffMinutes+ " minutes, ");
            System.out.println(diffSeconds+ " seconds.");
        }
        catch (Exception e) 
        {
            System.out.println(""+e);
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

上述程序的输出是.,

Difference : 3600000
0 days, 
1 hours, 
0 minutes, 
0 seconds.
Difference : -36000000
0 days, 
-10 hours, 
0 minutes, 
0 seconds.
Difference : 10800000
0 days, 
3 hours, 
0 minutes, 
0 seconds.
Run Code Online (Sandbox Code Playgroud)

执行时返回减去值 "checkTimeDifference("2013-10-30 10:15:00", "2013-10-30 12:15:00");"

为什么它的回报减值以及如何解决呢?

Jon*_*eet 9

这就是问题:

new SimpleDateFormat("yyyy-MM-dd hh:mm:ss")
Run Code Online (Sandbox Code Playgroud)

在hh这里的意思是"小时的一天12小时",让12指午夜,除非有什么东西来表明它的意思是12点.您的值13仅起作用,因为解析器处于宽松模式.你要:

new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")
Run Code Online (Sandbox Code Playgroud)

我也强烈建议您使用约达时间完成这个任务,无论如何,因为它使一个很大简单.