【发布时间】:2021-10-28 15:30:06
【问题描述】:
如何在 android 中检查两次之间的时间? 我有开放时间和关闭时间,我想使用特定的国家时区检查关闭时间是否已经过去。
public void timeElapse(String start, String end, String tz){
//SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm aa", Locale.getDefault());
SimpleDateFormat sdf = new SimpleDateFormat("hh:mm\\aa", Locale.getDefault());
try {
sdf.setTimeZone(tzs);
Date currentTimeDate = sdf.parse(start);
Date endTimeDate = sdf.parse(end);
int a = currentTimeDate.compareTo(endTimeDate); // false / current time has not passed end time.
int b = endTimeDate.compareTo(currentTimeDate); // true / end time has passed current time.
Log.e("timeElapse", "("+end+") A = " + a + " B = " + b);
} catch (ParseException ignored) {
}
}
第二次尝试
public void timeElapse(String start, String end, String tz){
SimpleDateFormat sdf = new SimpleDateFormat("hh:mm\\aa", Locale.getDefault());
try {
TimeZone tzs = TimeZone.getTimeZone(tz);
sdf.setTimeZone(tzs);
long currentTimeDate = sdf.parse(start).getTime();
long endTimeDate = sdf.parse(end).getTime();
if(currentTimeDate>endTimeDate){
Log.e("timeElapse", "Time has passed");
}else{
Log.e("timeElapse", "You are on time");
}
} catch (ParseException ignored) {
}
}
用法
timeElapse("10:00AM", "10:00PM", "Asia/Kuala_Lumpur");
timeElapse("10:00AM", "12:00PM", "Asia/Kuala_Lumpur");
timeElapse("11:30AM", "05:00PM", "Asia/Kuala_Lumpur");
timeElapse("10:00AM", "01:00AM", "Asia/Kuala_Lumpur");
我的代码不起作用。我收到错误 java.text.ParseException: Unparseable date: "10:00AM"
【问题讨论】:
-
一般情况下,您将时间保存在单个时区(通常为 UTC)中,并将当前时区转换为 UTC 以进行比较。将所有数据保存在一个时区中可以使代码更易于理解,并减少将来出现问题的可能性。
-
@GabeSechan 你能举个例子吗?
-
顺便考虑扔掉长期过时且臭名昭著的麻烦
SimpleDateFormat和朋友。看看您是否可以使用desugaring 或将ThreeTenABP 添加到您的Android 项目中,以便使用现代Java 日期和时间API 的java.time。使用起来感觉好多了。 -
您的尝试是否按预期工作?如果您得到任何意想不到的结果,请为我们说明。
-
@OleV.V.我的代码不起作用我收到错误
java.text.ParseException: Unparseable date: "10:00AM"
标签: java android datetime timezone