首页 > 解决方案 > 如何正确地将字符串与时间从文本文件转换为时间?

问题描述

我使用日历来获取时间。我想从文件(时间)中获取字符串并将其解析为日历对象。我将使用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");

    }

  }

}

标签: java

解决方案


找到的解决方案:

   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");

    }

  }

}

推荐阅读