计算考虑AM / PM的Java中的日期/时间差 [英] Calculate Date/Time Difference in Java considering AM/PM

查看:458
本文介绍了计算考虑AM / PM的Java中的日期/时间差的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用Date和Calendar类来计算java中两个日期/时间之间的差异。我的格式是2012-01-24 12:30:00 PM。

I want to calculate the difference between two date/time in java using Date and Calendar classes. The format that I have is "2012-01-24 12:30:00 PM".

我已经实现了自己的方法,也google与他人合作,但是没有得到正确的提示来处理AM和PM值。

I have implemented my own method and also google it to work with others, but haven't getting the right hint to handle AM and PM values.

日期/时间差异当时间有12(AM / PM)时遇到麻烦。例如,如果我有日期/时间2012-01-24 12:30:00 PM和2012-01-24 02:30:00 PM,则显示差值为10小时。

The date/time difference got troubled whenever the time have 12(AM/PM) in it. For example if I have date/time "2012-01-24 12:30:00 PM" and "2012-01-24 02:30:00 PM" it shows the difference is 10 hours.

考虑

Considering the code on this link how can it be modified to handle AM and PM.

要将字符串日期转换为日期,请使用以下代码:

To convert String date into Date I use following code:

    String sessionTimeStart = "2012-01-24 12:30:00 PM";
    String sessionTimerEndOrCurrent = "2012-01-24 02:30:00 PM";
    SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss a"); 

    Date d1 = null;
    Date d0 = null; 
    try {
        d1 = format.parse(sessionTimeStart);
        d0 = format.parse(sessionTimerEndOrCurrent);
    } catch (ParseException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    }


推荐答案

问题是你的日期格式:而不是 yyyy-MM-dd HH:mm:ss a 使用 yyyy-MM-dd hh:mm:ss a

The problem is your date format: instead of yyyy-MM-dd HH:mm:ss a use yyyy-MM-dd hh:mm:ss a.

HH 将是一天中的小时(0-23),而 hh 将是上午/下午(1-12)的小时。因此,使用您的日期格式02:30:00将被解析为只是,而不是被转换为PM版本(一天中的时间将是14:30:00)。

HH will be the hour in day (0-23) whereas hh will be the hour in AM/PM (1-12). Thus with your date format 02:30:00 will be parsed as just that instead of being converted to the PM version (which in hour of day would be 14:30:00).

这篇关于计算考虑AM / PM的Java中的日期/时间差的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆