我使用日历来获取时间。我想从文件(时间)获取字符串并将其解析为日历对象。我将使用Calendar类的after();
和before();
方法比较文件时间和当前时间
如果来自文件的时间晚于当前时间->打印(“来自文件的时间晚于当前时间。
如果来自文件的时间早于当前时间->打印(“来自文件的时间早于
我做了什么:
从文件返回的时间是正确的,但是他的问题是从文件返回的解析时间返回Thu Jan 01 20:59:00 GMT+07:00 1970
而不是我的当前年份
这就是if语句总是返回第一个参数的原因
如何正确地从文件中解析时间以比较两个时间对象?
这是我的完整代码:
public class Main {
public static void main(String[] args) throws IOException, ParseException {
Calendar calNow = Calendar.getInstance();
Date dateNow = new Date();
calNow.setTime(dateNow);
Calendar cal = Calendar.getInstance();
cal.add(Calendar.MINUTE, 5);
SimpleDateFormat df = new SimpleDateFormat("HH:mm");
String formatted = df.format(cal.getTime());
String formattedFut = df.format(calNow.getTime());
Path file = Paths.get("testFile.txt");
if (Files.exists(file) && Files.size(file) == 0) {
Files.write(file, List.of(formatted));
}
String timeFromFile = new String(Files.readAllBytes(Paths.get("testFile.txt")));
SimpleDateFormat sdf = new SimpleDateFormat("HH:mm");
Date dateOld = sdf.parse(timeFromFile);
Calendar calendarOld = Calendar.getInstance();
calendarOld.setTime(dateOld);
if (dateNow.after(dateOld)) {
System.out.println(dateNow + " is after day from file");
}
if (dateNow.before(dateOld)) {
System.out.println(dateNow + " is before day from file");
}
}
}
答案 0 :(得分:0)
解决方案:
public class Main {
public static void main(String[] args) throws IOException, ParseException {
SimpleDateFormat("HH:mm").format(Calendar.getInstance().getTime());
Calendar calendarNow = Calendar.getInstance();
Date dateNow = new Date();
calendarNow.setTime(dateNow);
Calendar cal = Calendar.getInstance();
cal.add(Calendar.MINUTE, 5);
SimpleDateFormat df = new SimpleDateFormat("EEE MMM dd HH:mm:ss z yyyy", Locale.ENGLISH);
String formatted = df.format(cal.getTime());
String formattedFut = df.format(calendarNow.getTime());
Path file = Paths.get("testFile.txt");
if (Files.exists(file) && Files.size(file) == 0) {
Files.write(file, List.of(formatted));
}
Calendar calendarOld = Calendar.getInstance();
String timeFromFile = new String(Files.readAllBytes(Paths.get("testFile.txt")));
SimpleDateFormat sdf = new SimpleDateFormat("EEE MMM dd HH:mm:ss z yyyy", Locale.ENGLISH);
calendarOld.setTime(sdf.parse(timeFromFile));
if (calendarNow.after(calendarOld)) {
System.out.println(timeFromFile + " \ntime passed");
}
if (calendarNow.before(calendarOld)) {
System.out.println(timeFromFile + " \n time NOT PASSED");
}
}
}