如何知道当前时间是否为特定时区的上午5点。

huangapple go评论63阅读模式
英文:

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

问题

以下是翻译好的部分:

我的系统时区是UTC。
我如何使用Java日期时间API知道在给定时区是否是上午5点?
我如何使用区域日期时间进行这个操作?
现在新加坡是不是早上5点?
现在印度是不是早上5点?
现在奥地利是不是早上5点?
谢谢。
这是我的最终逻辑。在下面的解决方案中工作后。

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("在 " + z.getId() + " 时区,现在是5点到5点5分之间。");
            }
        }
    }
}
英文:

My system time zone is utc.
How can I know using java date time api if its 5am in a given timezone?

How can I use zone date time for this?

Is it 5am in singapore now?
Is it 5am in india now?
Is it 5am in austria now?

Thanks

This is my final logic. After working on the solutions below.

    public class MorningReminderScheduler {

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

答案1

得分: 4

你可以使用LocalTime类来查找任何支持的时区中的本地时间。例如:

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

要判断在新加坡是否是早上5点,你可能希望应用一些阈值,因为时间恰好在早上5点的时间段非常短。你可以计算早上5点和给定的时间之间的差异,如果差异足够"小",就可以认为是早上5点。例如,以下代码将在早上4:50到5:10之间的任何时间都判定为早上5点:

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

You can use the LocalTime class to find the local time in any support time zone. For example:

String zoneId = &quot;Asia/Singapore&quot;;
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. 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. For example, this will claim the time is 5am at any time between 4:50 and 5:10:

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

答案2

得分: 1

你可以使用所需时区的zoneId来获取时间。使用DateFormatter格式化日期,然后验证是否为凌晨5点。示范代码如下:

public static void getCurrentTimeWithTimeZone(){
    System.out.println("-----使用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("洛杉矶当地时间: " + formattedTime);
    if(formattedTime.equals("05:00:00"))
        System.out.println("洛杉矶时间是凌晨5点");
}
英文:

You can use zoneId of the timezone you want to know the time of. Format the date using a DateFormatter and then verify if it's 5:00 AM. A sample code can be like below:

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

}

答案3

得分: 1

假设你所说的 5 am 指的是 5:00,即你不考虑秒和纳秒,你可以比较新加坡的时间的小时和分钟,分别与 50 进行比较,以确定是否为早上 5 点

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) {
        // 新加坡的时区偏移为 UTC +8
        LocalTime nowAtSingapore = OffsetTime.now().withOffsetSameInstant(ZoneOffset.ofHours(8)).toLocalTime();
        System.out.println("现在在新加坡: " + nowAtSingapore);
        System.out.println("现在在新加坡 (HH:mm): " + DateTimeFormatter.ofPattern("HH:mm").format(nowAtSingapore));

        // 检查当前是否为新加坡的 5:00
        if (nowAtSingapore.getHour() == 5 && nowAtSingapore.getMinute() == 0) {
            System.out.println("现在是新加坡的 5:00");
        }
    }
}

输出:

现在在新加坡: 05:24:43.217733
现在在新加坡 (HH:mm): 05:24

注意: LocalTime.toString() 的默认格式是 HH:mm:ss.SSSSSS,其中 SSSSSS 表示纳秒。为了获得自定义模式的字符串,我们使用 DateTimeFormatter#ofPattern

英文:

Assuming you mean 5:00 when you say 5 am i.e. 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.

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(&quot;Now at Singapore: &quot; + nowAtSingapore);
		System.out.println(&quot;Now (HH:mm) at Singapore: &quot; + DateTimeFormatter.ofPattern(&quot;HH:mm&quot;).format(nowAtSingapore));

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

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. In order to get a string in a custom pattern, we use DateTimeFormatter#ofPattern.

答案4

得分: 1

编辑: 对于您的定时任务,我建议您跟踪您在该时区发送文本(短信)消息的上次日期。因此,如果现在已经过了第二天的凌晨5点 之后,发送下一条消息(并更新存储的日期)。这将确保即使作业恰好不在您的5分钟容差区间内运行,消息也会被发送。而且,如果作业恰好运行两次,消息也不会发送两次。时间很棘手,因为我们无法精确地在指定的时间发生事情,所以我们必须考虑这些可能性。

原回答:

不,现在不是印度或您提到的其他时区的上午5点。某个时区中的上午5点持续的时间为0,因此现在是那个时间的概率为0。

在许多平台上,自Java 9以来,Java可以以微秒精度读取时间。因此,即使现在并不完全是上午5点,它仍然给我们留下了时间读取为上午5点的0.000000001%的概率。这仍然足够小,可以说几乎永远不会发生。

因此,我建议您使用一些容差:如果时间与上午5点足够接近,则将其视为上午5点。例如:

final LocalTime time = LocalTime.of(5, 0); // 上午5点
final Duration tolerance = Duration.ofMillis(600); // 例如,0.6秒

ZoneId zone = ZoneId.of("Asia/Kolkata"); // 印度

LocalTime nowInZone = LocalTime.now(zone);
if (nowInZone.isBefore(time.minus(tolerance)) || nowInZone.isAfter(time.plus(tolerance))) {
    System.out.println("不,现在不是" + time + "在" + zone);
} else {
    System.out.println("是的,现在是" + nowInZone + "在" + zone);
}

当我刚刚运行了这段代码时,输出很可能是:

不,现在不是05:00在Asia/Kolkata

请注意,只有在容差不跨越午夜(12点)时,代码才能正确运行。例如,如果时间是凌晨0:01,并且容差是2分钟,我们将检查时间是否在23:59之后 并且 在0:03之前。没有时间可以同时满足这两个条件,因此即使时间在这4分钟的间隙内,我们仍然会得到的结果。但对于上午5点和小于5小时的容差,它是有效的。

英文:

EDIT: For your cron job I suggest you keep track of the last date you sent the text (SMS) message for that time zone. So if it is now past 5 AM on the following day, send the next message (and update the date stored). 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. 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. The point in time of 5 AM in some time zone lasts 0, so the probability that it is that time is 0.

On many platforms Java can since Java 9 read the time with microsecond precision. 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. 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. 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(&quot;Asia/Kolkata&quot;); // India
	
	LocalTime nowInZone = LocalTime.now(zone);
	if (nowInZone.isBefore(time.minus(tolerance)) || nowInZone.isAfter(time.plus(tolerance))) {
		System.out.println(&quot;No, it is not &quot; + time + &quot; in &quot; + zone);
	} else {
		System.out.println(&quot;Yes, it is &quot; + nowInZone + &quot; in &quot; + zone);
	}

When I ran the code just now, output was the likely:

> No, it is not 05:00 in Asia/Kolkata

Beware that the code only works correctly so long as the tolerance doesn’t cross midnight (12 AM). 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. No time can be both, so we’d always get No even if the time was within that 4 minutes gap. But for 5 AM and a tolerance less than 5 hours it does work.

huangapple
  • 本文由 发表于 2020年8月17日 04:11:58
  • 转载请务必保留本文链接:https://go.coder-hub.com/63441526.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定