计算java中两个给定时间的差异b / w [英] Calculate the difference b/w two given times in java
本文介绍了计算java中两个给定时间的差异b / w的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试计算给定两次的差异,我发现一些问题。
假设我们有时间值是11:AM和10:00 AM
我可以计算,但AM,PM有一点混乱
提前感谢
I am trying to calculate the difference between given two times and i find some problem in it. Suppose we have times value are "11:AM" and 10:00 AM". I am able to calculate but there is a bit of confusion in AM ,PM. Thanks in advance
我正在使用以下代码:
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
public class StringToDate {
public static String timeDiff(String time1, String time2) {
String Time = null;
int difference;
String a1 = time1.substring(6);
String a2 = time2.substring(6);
try {
// Define a date format the same as the expected input
SimpleDateFormat sdf = new SimpleDateFormat("HH:mm a");
// Get time values of the date objects
long l1 = sdf.parse(time1).getTime();
long l2 = sdf.parse(time2).getTime();
difference = (int) (l2 - l1);
difference = (difference < 0 ? -difference : difference) / 60000;
if (difference > 60) {
int Hour = difference / 60;
int Mins = difference % 60;
if (Mins == 0)
Time = Hour + " Hours";
else
Time = Hour + " Hours" + " " + Mins + " Mins";
} else {
Time = difference + " " + "Mins";
}
} catch (ParseException e) {
e.printStackTrace();
}
return Time;
}
public static void main(String[] args) {
String diff = StringToDate.timeDiff("10:00 AM", "01:00 PM");
System.out.println("Difference: " + diff);
}
}
推荐答案
您可以获取开始和开始的日期对象时间结束。
然后得到时间在millis&
You can get date objects for both start & end time. Then get time in millis & subtract.
Millis的差异= endDate.getTime() - startDate.getTime()
Difference in Millis = endDate.getTime() - startDate.getTime()
转换差异到小时/分钟。
Convert the difference to hours/minutes.
这篇关于计算java中两个给定时间的差异b / w的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文