我试图计算给定两次之间的差异,我发现它有一些问题.假设我们有时间值是"11:AM"和10:00 AM".我能够计算但是AM,PM有点混乱.提前感谢
我使用以下代码:
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);
}
Run Code Online (Sandbox Code Playgroud)
}
小智 6
您可以获取开始和结束时间的日期对象.然后以毫秒计算并减去时间.
Millis的差异= endDate.getTime() - startDate.getTime()
将差异转换为小时/分钟.
| 归档时间: |
|
| 查看次数: |
4203 次 |
| 最近记录: |