繁体   English   中英

获取当前时间并检查时间是否已过特定时间段

[英]Get current time and check if time has passed a certain period

下面的这段代码获取该地区的当前时间和时区

    Date date = new Date();
    DateFormat df = new SimpleDateFormat("HH:mm:ss");

    df.setTimeZone(TimeZone.getDefault());

    System.out.println("Time: " + df.format(date)); 

现在是下午 1:01(打字时)

我需要帮助的是在代码中实现一个功能来检查当前时间是否已经过去,例如 1:00PM

但我不知道从哪里开始,你能帮我吗?

使用 Java 8+ Time API 类LocalTime

LocalTime refTime = LocalTime.of(13, 0); // 1:00 PM
// Check if now > refTime, in default time zone
LocalTime now = LocalTime.now();
if (now.isAfter(refTime)) {
    // passed
}
// Check if now >= refTime, in pacific time zone
LocalTime now = LocalTime.now(ZoneId.of("America/Los_Angeles"))
if (now.compareTo(refTime) >= 0) {
    // passed
}

我看到它已经用 Time 回答了,但作为一个教学点,如果你真的想使用 Date,你可以做这样的事情:

public static void main(String[] args) {
    Date date = new Date();
    DateFormat df = new SimpleDateFormat("HH:mm:ss");
    df.setTimeZone(TimeZone.getDefault());
    System.out.println("Time: " + df.format(date));

    //If you print the date you'll see how it is formatted
    //System.out.println(date.toString());

    //So you can just split the string and use the segment you want
    String[] fullDate = date.toString().split(" ");

    String compareAgainstTime = "01:00PM";

    System.out.println(isPastTime(fullDate[3],compareAgainstTime));
    }

public static boolean isPastTime(String currentTime, String comparedTime) {
    //We need to make the comparison time into the same format as the current time: 24H instead of 12H:
    //then we'll just convert the time into only minutes to that we can more easily compare;
    int comparedHour = comparedTime[-2].equals("AM") ? String.valueOf(comparedTime[0:2]) : String.valueOf(comparedTime[0:2] + 12 );
    int comparedMin = String.valueOf(comparedTime[3:5]);
    int comparedT = comparedHour*60 + comparedMin;

    //obviously currentTime is alredy the correct format; just need to convert to minutes
    int currentHour = String.valueOf(currentTime[0:2]);
    int currentMin = String.valueOf(currentTime[3:5]);
    int currentT = currentHour*60 + currentMin;

    return (currentT > comparedT);
}

这有点混乱,不得不混入字符串之类的东西,但这是可能的。 您还必须小心对比较时间进行零填充,或者只是在函数中检查

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM