本文介紹了獲得持續時間 2 次的處理方法,對大家解決問題具有一定的參考價值,需要的朋友們下面隨著小編來一起學習吧!
問題描述
限時送ChatGPT賬號..
如何獲取 YYYYMMDDTHHMMSS
格式的兩個字符串的持續時間?
How can I get the duration of two Strings in the format YYYYMMDDTHHMMSS
?
我正在嘗試使用 Calendar 類并檢查 getTimeInMillis()
.我遇到的問題是它不一致.知道我做錯了什么嗎?每次我運行這個程序時,我都會得到 40-70 行輸出到控制臺,而實際上應該沒有.
I′m trying with using the Calendar class and checking the getTimeInMillis()
. Problem I am having with this is that it is not consistent. Any idea what I am doing wrong?
Every time I run this program I get 40-70 lines of output to console when it should be none.
public class DurationTester {
/**
* Get the duration between two given times
* @param time1 yyyymmddThhmmss
* @param time2 yyyymmddThhmmss
* @return minutes between time1 and time2
*/
public static int getDuration(String time1, String time2){
int yyyy1 = Integer.parseInt(time1.substring(0,4));
int mm1 = Integer.parseInt(time1.substring(4,6));
int dd1 = Integer.parseInt(time1.substring(6,8));
int hh1 = Integer.parseInt(time1.substring(9,11));
int min1 = Integer.parseInt(time1.substring(11,13));
int yyyy2 = Integer.parseInt(time2.substring(0,4));
int mm2 = Integer.parseInt(time2.substring(4,6));
int dd2 = Integer.parseInt(time2.substring(6,8));
int hh2 = Integer.parseInt(time2.substring(9,11));
int min2 = Integer.parseInt(time2.substring(11,13));
Calendar cal1 = Calendar.getInstance();
cal1.set(yyyy1, mm1, dd1, hh1, min1, 0);
Calendar cal2 = Calendar.getInstance();
cal2.set(yyyy2, mm2, dd2, hh2, min2, 0);
long milliSec = cal1.getTimeInMillis()-cal2.getTimeInMillis();
long nonNegativeMS = Math.abs(milliSec);
long seconds = nonNegativeMS / 1000;
long minutes = seconds / 60;
return (int)minutes;
}
public static void main(String[] args){
String t1 = "20130108T150000";
String t2 = "20130108T131500";
int errors = 0;
for(int i=0; i<5000; i++){
int duration = getDuration(t1,t2);
if(duration == 104){
System.out.println("ERROR: Should only be 105 ("+errors++ +")");
}
}
}
}
推薦答案
這是一個記錄的錯誤.
嘗試在設置之前清除日歷:
Try clearing the calendar before set:
cal1.clear();
cal1.set(yyyy1, mm1, dd1, hh1, min1, 0);
cal2.clear();
cal2.set(yyyy2, mm2, dd2, hh2, min2, 0);
這篇關于獲得持續時間 2 次的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!
【網站聲明】本站部分內容來源于互聯網,旨在幫助大家更快的解決問題,如果有圖片或者內容侵犯了您的權益,請聯系我們刪除處理,感謝您的支持!