简体   繁体   English

我怎么知道当前时间是否是特定时区的凌晨 5 点

[英]How can i know if current time is 5 am in specific time zone

My system time zone is utc.我的系统时区是UTC。 How can I know using java date time api if its 5am in a given timezone?如果在给定时区的凌晨 5 点,我如何知道使用 java 日期时间 api?

How can I use zone date time for this?如何为此使用区域日期时间?

Is it 5am in singapore now?新加坡现在是早上五点吗? Is it 5am in india now?印度现在是凌晨 5 点吗? Is it 5am in austria now?奥地利现在是凌晨五点吗?

Thanks谢谢

This is my final logic.这是我最后的逻辑。 After working on the solutions below.在解决以下解决方案之后。

    public class MorningReminderScheduler {

    @Scheduled( cron="0 0/5 * * * *  ")
    public static void main(String args[]){
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("HH:mm:ss");
        for (String zoneId : ZoneId.getAvailableZoneIds()) {
            ZoneId z = ZoneId.of(zoneId);
            // LocalDateTime -> ZonedDateTime
            LocalTime l= LocalTime.now(z);
            if(l.getHour()==5 && l.getMinute()<5){
                System.out.println("its between 5 hour to 5 hour 5 min in  = " + z.getId());
            }
        }
    }
}

You can use the LocalTime class to find the local time in any support time zone.您可以使用 LocalTime class 来查找任何支持时区的当地时间。 For example:例如:

String zoneId = "Asia/Singapore";
LocalTime timeInSingapore = LocalTime.now(ZoneId.of(zoneId));

To find if it's 5 am in Singapore, you'll probably want to apply some threshold because the time is exactly 5 am for a very short period of time.要确定新加坡是否是凌晨 5 点,您可能需要应用一些阈值,因为在很短的时间内时间正好是凌晨 5 点。 What you could do is calculate the difference between 5 am and the given moment in time, and if the difference is "small enough" you can claim it's 5 am.您可以做的是计算早上 5 点与给定时刻之间的差异,如果差异“足够小”,您可以声称它是早上 5 点。 For example, this will claim the time is 5am at any time between 4:50 and 5:10:例如,这将声明时间是凌晨 5 点,在 4:50 到 5:10 之间的任何时间:

LocalTime fiveAm = LocalTime.of(5, 0);
long minutesBetween = Math.abs(ChronoUnit.MINUTES.between(fiveAm, timeInSingapore));
if (minutesBetween <= 10) {
    // close enough
    System.out.println("It's 5am in " + zoneId);
}

You can use zoneId of the timezone you want to know the time of.您可以使用您想知道时间的时区的 zoneId。 Format the date using a DateFormatter and then verify if it's 5:00 AM.使用 DateFormatter 格式化日期,然后验证它是否为 5:00 AM。 A sample code can be like below:示例代码如下所示:

public static void getCurrentTimeWithTimeZone(){
    System.out.println("-----Current time of a different time zone using LocalTime-----");
    ZoneId zoneId = ZoneId.of("America/Los_Angeles");
    LocalTime localTime=LocalTime.now(zoneId);
    DateTimeFormatter formatter = DateTimeFormatter.ofPattern("HH:mm:ss");
    String formattedTime=localTime.format(formatter);
    System.out.println("Current time of the day in Los Angeles: " + formattedTime);
    if(formattedTime.equals("05:00:00")
       System.out.println("It is 5 AM in Los Angeles");

}

Assuming you mean 5:00 when you say 5 am ie you are not considering the seconds and nanoseconds, you can compare the hour and minute of time at Singapore with 5 and 0 respectively to evaluate if it is 5 am .假设您说5 am时的意思是5:00即您不考虑秒和纳秒,您可以将新加坡的小时和分钟分别与50进行比较,以评估它是否是5 am

import java.time.LocalTime;
import java.time.OffsetTime;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;

public class Main {
    public static void main(String[] args) {
        // Singapore has the Zone Offset of UTC +8
        LocalTime nowAtSingapore = OffsetTime.now().withOffsetSameInstant(ZoneOffset.ofHours(8)).toLocalTime();
        System.out.println("Now at Singapore: " + nowAtSingapore);
        System.out.println("Now (HH:mm) at Singapore: " + DateTimeFormatter.ofPattern("HH:mm").format(nowAtSingapore));

        // Check if it is 5:00 at Singapore now
        if (nowAtSingapore.getHour() == 5 && nowAtSingapore.getMinute() == 0) {
            System.out.println("It's 5:00 at Singapore");
        }
    }
}

Output: Output:

Now at Singapore: 05:24:43.217733
Now (HH:mm) at Singapore: 05:24

Note: that the default format of LocalTime.toString() is HH:mm:ss.SSSSSS where SSSSSS denotes nanoseconds.注意: LocalTime.toString LocalTime.toString()的默认格式是HH:mm:ss.SSSSSS ,其中SSSSSS表示纳秒。 In order to get a string in a custom pattern, we use DateTimeFormatter#ofPattern .为了获取自定义模式中的字符串,我们使用DateTimeFormatter#ofPattern

EDIT: For your cron job I suggest you keep track of the last date you sent the text (SMS) message for that time zone.编辑:对于您的 cron 工作,我建议您跟踪您为该时区发送文本(SMS)消息的最后日期。 So if it is now past 5 AM on the following day , send the next message (and update the date stored).因此,如果现在已经过了第二天早上5 点,请发送下一条消息(并更新存储的日期)。 This will make sure that the message is sent even if the job doesn't happen to run exactly within your 5 minutes tolerance interval.这将确保即使作业没有恰好在您的 5 分钟容差间隔内运行,也会发送消息。 Also it will not be sent twice if the job happens to run twice.如果作业恰好运行两次,也不会发送两次。 Time is tricky in that we never get things to happen exactly at the time specified, so we have to take these possibilities into account.时间很棘手,因为我们永远不会让事情在指定的时间准确地发生,所以我们必须考虑到这些可能性。

Original answer原始答案

No, it is not 5 AM in India or one of the other time zones you mentioned.不,它不是印度的凌晨 5 点,也不是您提到的其他时区之一。 The point in time of 5 AM in some time zone lasts 0, so the probability that it is that time is 0.某个时区凌晨 5 点的时间点持续为 0,因此该时间点的概率为 0。

On many platforms Java can since Java 9 read the time with microsecond precision.在许多平台上 Java 可以自 Java 9 以微秒精度读取时间。 So even though it is not exactly 5 AM, it leaves us with a probability of 0.000000001 % that the time read is 5 AM.因此,即使不完全凌晨 5 点,我们也有 0.000000001 % 的概率认为读取的时间是凌晨 5 点。 It's still minute enough to say that it will practically never happen.可以说它几乎永远不会发生。

So I suggest that you work with some tolerance: If the time is sufficiently close to 5 AM, you regard it as 5 AM.所以我建议你保持一定的宽容度:如果时间足够接近凌晨 5 点,你就认为它是凌晨 5 点。 For example:例如:

    final LocalTime time = LocalTime.of(5, 0); // 5 AM
    final Duration tolerance = Duration.ofMillis(600); // 0.6 seconds as an example
    
    ZoneId zone = ZoneId.of("Asia/Kolkata"); // India
    
    LocalTime nowInZone = LocalTime.now(zone);
    if (nowInZone.isBefore(time.minus(tolerance)) || nowInZone.isAfter(time.plus(tolerance))) {
        System.out.println("No, it is not " + time + " in " + zone);
    } else {
        System.out.println("Yes, it is " + nowInZone + " in " + zone);
    }

When I ran the code just now, output was the likely:刚才运行代码时,output 很可能是:

No, it is not 05:00 in Asia/Kolkata不,在亚洲/加尔各答不是 05:00

Beware that the code only works correctly so long as the tolerance doesn't cross midnight (12 AM).请注意,只要容差不超过午夜(上午 12 点),代码才能正常工作。 For example, it the time was 0:01 AM and the tolerance was 2 minutes, we'd check whether the time was after 23:59 and before 0:03.例如,时间为 0:01 AM,容差为 2 分钟,我们将检查时间是否在 23:59 之后0:03 之前。 No time can be both, so we'd always get No even if the time was within that 4 minutes gap.没有时间可以两者兼而有之,所以即使时间在 4 分钟的间隔内,我们也总是会得到“否”。 But for 5 AM and a tolerance less than 5 hours it does work.但是对于凌晨 5 点和小于 5 小时的容差,它确实有效。

暂无
暂无

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

相关问题 如何获取特定区域的特定格式的当前时间? - How can I get the current time in particular format, for a particular zone? 如果我在其他国家/地区,我如何知道特定国家/地区的时间? - How can i know time in a specific country if i am in a differenet country? 如何在ICU4J中获得“当前”IANA时区缩写? - How can I get the “current” IANA time zone abbreviation throughout time in ICU4J? 如何判断Java日期和时区是否在当前时间之前? - How can I tell if a Java Date and time zone is before the current time? 如何在Joda时间中将日期时间从时区A转换为时区B? - How can I convert date time from time zone A to time zone B in Joda time? 如何检查当前时区的毫秒时间戳是否在午夜? - How can I check if a millisecond timestamp is at midnight in my current time zone? 我如何告诉 Joda Time 我给它的时间是针对特定时区偏移量的,即使字符串中没有给出偏移量? - How do I tell Joda Time that the time I am giving it is for a specific time zone offset, even though the offset isn't given in the String? 如何在特定时区(“欧洲/巴黎”)中获取今天的 startDate 和 endDate 的 UTC 瞬间 - How can I get UTC Instant of startDate and endDate of today in a specific time zone (“Europe/Paris”) 如何从时区获取时区ID - How do I get the time zone id from a time zone 如何在postgres中节省没有时区的时间。 我正在使用休眠的Spring MVC - how to save time without time zone in postgres . i am using hibernate Spring MVC
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM