英文:
Difference between two times stored as Strings
问题
我有两个形如“dd-MM-YYYY HH:mm:ss”的字符串。如何找出这两个字符串之间的小时差异?
英文:
I have two strings of the form "dd-MM-YYYY HH:mm:ss". How can I find the difference in hours between the two Strings ?
答案1
得分: 1
你可以将 String
转换为 Date
对象,然后进行比较。类似以下方式:
SimpleDateFormat sdformat = new SimpleDateFormat("dd-MM-YYYY HH:mm:ss");
Date d1 = sdformat.parse("04-05-2020 02:33:12");
Date d2 = sdformat.parse("05-05-2020 02:33:12");
System.out.println("The date 1 is: " + sdformat.format(d1));
System.out.println("The date 2 is: " + sdformat.format(d2));
if(d1.compareTo(d2) > 0) {
System.out.println("Date 1 occurs after Date 2");
} else if(d1.compareTo(d2) < 0) {
System.out.println("Date 1 occurs before Date 2");
} else if(d1.compareTo(d2) == 0) {
System.out.println("Both dates are equal");
}
英文:
You can converted the String
into Date
objects, then you may compare them.
Something like below
SimpleDateFormat sdformat = new SimpleDateFormat("dd-MM-YYYY HH:mm:ss");
Date d1 = sdformat.parse("04-05-2020 02:33:12");
Date d2 = sdformat.parse("05-05-2020 02:33:12");
System.out.println("The date 1 is: " + sdformat.format(d1));
System.out.println("The date 2 is: " + sdformat.format(d2));
if(d1.compareTo(d2) > 0) {
System.out.println("Date 1 occurs after Date 2");
} else if(d1.compareTo(d2) < 0) {
System.out.println("Date 1 occurs before Date 2");
} else if(d1.compareTo(d2) == 0) {
System.out.println("Both dates are equal");
}
答案2
得分: 0
使用SimpleDateFormat
和Date
,你可以这样做:
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
public static long date_hour_diff(String start_date, String end_date) {
SimpleDateFormat simple_date_format = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss");
try {
Date parsed_start_date = simple_date_format.parse(start_date);
Date parsed_end_date = simple_date_format.parse(end_date);
long time_diff = parsed_end_date.getTime() - parsed_start_date.getTime();
long diff_hours = (time_diff / (1000 * 60 * 60)) % 24;
return diff_hours;
} catch (ParseException e) {
Log.e(TAG, "Date is not valid.");
}
}
英文:
You can do it using SimpleDateFormat
and Date
:
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
public static long date_hour_diff(String start_date, String end_date) {
SimpleDateFormat simple_date_format = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss");
try {
Date parsed_start_date = simple_date_format.parse(start_date);
Date parsed_end_date = simple_date_format.parse(end_date);
long time_diff = d2.getTime() - d1.getTime();
long diff_hours = (time_diff / (1000 * 60 * 60)) % 24;
return diff_hours;
} catch (ParseException e) {
Log.e(TAG, "Date is not valid.");
}
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论