java - 如何正确地将字符串与时间从文本文件转换为时间?
问题描述
我使用日历来获取时间。我想从文件(时间)中获取字符串并将其解析为日历对象。我将使用Calendar 类的方法after();
比较文件中的时间和当前时间before();
如果来自文件的时间在当前时间之后 -> 打印(“来自文件的时间在当前时间之后。
如果文件中的时间早于当前时间 -> 打印(“文件中的时间早于
我做了什么:
- 我创建了文件
- 得到当前时间
- 将当前时间解析为字符串
- 将字符串保存到文件中
- 得到当前时间
- 从文件中读取 etx
- 将文本从文件解析到 Date 对象
从文件返回的时间是正确的,但他的问题是从文件返回的解析时间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");
}
}
}
解决方案
找到的解决方案:
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");
}
}
}
推荐阅读
- mongodb - 如何在 Docker 中将 Debezium 连接到 MongoDB?
- javascript - 使用 Javascript 计算 IRR
- android - ExoPlayer(Xamarin) 无法打开 http 链接 - 如何解决?
- python - 使用 TKinter python 的串行监视器不起作用
- webpack - Webpack 开发服务器允许浏览器使用从非本地服务器导入地图文件
- c# - ASP.NET Core 客户端用于 SoapService 双调用方法
- python - python -m 并在 __init__.py 中导入
- azure - ARM Resource Not Found 在尝试使用Outputs时,已经尝试了很多
- dtn - 如何在 ONE 模拟器中使用外部实时追踪移动模型?
- r - 如何避免转换为矩阵中的原子向量(r 编程)