本文介绍了使用yyyy-MM-dd hh:mm:ss格式解析日期的意外差异的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

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

why its return minus value and how to solve it?

推荐答案

这是问题所在:

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

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

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.

这篇关于使用yyyy-MM-dd hh:mm:ss格式解析日期的意外差异的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-05 05:01