【问题标题】:Get current time and check if time has passed a certain period获取当前时间并检查时间是否已经过了一段时间
【发布时间】:2019-12-06 21:11:15
【问题描述】:

以下代码获取该地区的当前时间和时区

    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:00

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

【问题讨论】:

标签: java date


【解决方案1】:

使用 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
}

【讨论】:

    【解决方案2】:

    我看到它已经用 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);
    }
    

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

    【讨论】:

    • 您正在使用糟糕的日期时间类,几年前这些类已被现代 java.time 类所取代。请参阅正确的Answer by Andreas。使用LocalTime.now().isAfter( LocalTime.of( 1 , 0 ) ) 要简单得多。
    • 再次......正如我在回答中提到的那样,我写这个答案只是为了表明它可以通过某种方式完成,因为他不确定这怎么可能。我同意安德烈亚斯是更好的答案
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-11-06
    • 2021-06-29
    • 2012-01-18
    • 1970-01-01
    相关资源
    最近更新 更多