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

时间:2013-10-30 07:12:15

标签: 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);
        }
    }
}

上述程序的输出是。,

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.
执行"checkTimeDifference("2013-10-30 10:15:00", "2013-10-30 12:15:00");"

时,

返回减去值

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

2 个答案:

答案 0 :(得分:9)

这是问题所在:

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

此处hh表示" 12小时工作时间"所以12表示午夜,除非有东西表明它意味着下午12点。您的值13仅起作用,因为解析器处于宽松模式。你想要:

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

我还强烈建议您使用Joda Time执行此任务,因为它使 lot 更简单。

答案 1 :(得分:3)

SimpleDateFormat模式更改为yyyy-MM-dd HH:mm:ss可解决问题。

这是因为在yyyy-MM-dd hh:mm:ss案例中,12被评估为0