两次存储为字符串之间的差异
Difference between two times stored as Strings
我有两个形式为“dd-MM-YYYY HH:mm:ss”的字符串。我怎样才能找到两个字符串之间的小时差异?
您可以使用 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 = 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.");
}
}
您可以将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");
}
我有两个形式为“dd-MM-YYYY HH:mm:ss”的字符串。我怎样才能找到两个字符串之间的小时差异?
您可以使用 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 = 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.");
}
}
您可以将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");
}