考虑 AM/PM 计算 Java 中的日期/时间差

2023-02-10Java开发问题
2

本文介绍了考虑 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".

我已经实现了我自己的方法,并在谷歌上搜索它以与其他人一起工作,但没有得到正确的提示来处理 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.

考虑 此链接上的代码 如何修改它来处理 AM 和 PM.

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 将是 AM/PM (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 中的日期/时间差的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

The End

相关推荐

如何使用 JAVA 向 COM PORT 发送数据?
How to send data to COM PORT using JAVA?(如何使用 JAVA 向 COM PORT 发送数据?)...
2024-08-25 Java开发问题
21

如何使报表页面方向更改为“rtl"?
How to make a report page direction to change to quot;rtlquot;?(如何使报表页面方向更改为“rtl?)...
2024-08-25 Java开发问题
19

在 Eclipse 项目中使用西里尔文 .properties 文件
Use cyrillic .properties file in eclipse project(在 Eclipse 项目中使用西里尔文 .properties 文件)...
2024-08-25 Java开发问题
18

有没有办法在 Java 中检测 RTL 语言?
Is there any way to detect an RTL language in Java?(有没有办法在 Java 中检测 RTL 语言?)...
2024-08-25 Java开发问题
11

如何在 Java 中从 DB 加载资源包消息?
How to load resource bundle messages from DB in Java?(如何在 Java 中从 DB 加载资源包消息?)...
2024-08-25 Java开发问题
13

如何更改 Java 中的默认语言环境设置以使其保持一致?
How do I change the default locale settings in Java to make them consistent?(如何更改 Java 中的默认语言环境设置以使其保持一致?)...
2024-08-25 Java开发问题
13