Java 11 时间 – 是否为今天的时间戳(long)。

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

Java 11 time - is (long)timestamp today

问题

我在一个Mongo文档字段中有一个cron作业字符串。我通过以下方式获得下一个有效的(长时间)时间:

CronExpression exp = new CronExpression(billing.getReminder());
				
long nextReminder = exp.getNextValidTimeAfter(new Date()).getTime();

我的想法是检查这个“nextReminder”是否是今天,如果是,就创建一些任务。在Java 11中,最好的方法是什么?

英文:

I have a cronjob string saved in a mongo document field. I get the next valid (long)time by

CronExpression exp = new CronExpression(billing.getReminder());
			
long nextReminder = exp.getNextValidTimeAfter(new Date()).getTime();

My idea is to check if this "nextReminder" isToday() then create some task.
What is the best way to check it with java 11?

答案1

得分: 2

你可以使用 java.time 进行比较...

有一个 Instant 表示一个时间点,就像 epoch 毫秒时间戳一样(表示为你的 long nextReminder),以及 OffsetDateTime.now() 表示实际的当前时刻 now,以及 LocalDate 表示仅包含日期部分。

你可以使用类似下面的方法来判断 nextReminder 是否是今天

/**
 * <p>
 * 检查给定时间戳(以 epoch 毫秒表示)的日期(或日期部分)
 * 是否与&lt;em&gt;今天&lt;/em&gt;相同(即执行该方法的当天)。&lt;br&gt;
 * <strong>需要偏移量以便进行比较&lt;/strong&gt;
 * </p>
 *
 * @param epochMillis	要检查的以 epoch 毫秒表示的时间戳
 * @param zoneOffset	要用作比较基准的偏移量
 * @return &lt;code&gt;true&lt;/code&gt; 如果参数的日期与今天的日期相等,
 *         否则为 &lt;code&gt;false&lt;/code&gt;
 */
public static boolean isToday(long epochMillis, ZoneOffset zoneOffset) {
	// 根据给定的偏移量从参数中提取日期部分
	LocalDate datePassed = Instant.ofEpochMilli(epochMillis)
								.atOffset(zoneOffset)
								.toLocalDate();
	// 然后根据给定的偏移量从 &quot;now&quot; 中提取日期部分
	LocalDate today = Instant.now()
								.atOffset(zoneOffset)
								.toLocalDate();
	// 然后返回相等性检查的结果
	return datePassed.equals(today);
}

然后只需像这样调用它:

boolean isNextReminderToday = isToday(nextReminder, ZoneOffset.systemDefault());

这将使用系统的时区偏移。或许,ZoneOffset.UTC 也是一个明智的选择。

英文:

You could use java.time for a comparison...

There is an Instant representing a moment in time like a timestamp in epoch milliseconds does (&rArr; your long nextReminder) as well as OffsetDateTime.now() for the actual moment now and LocalDate as the part describing the date-part only.

You could find out if the nextReminder is today by using a method like this:

/**
 * &lt;p&gt;
 * Checks if the day (or date) of a given timestamp (in epoch milliseconds)
 * is the same as &lt;em&gt;today&lt;/em&gt; (the day this method is executed).&lt;br&gt;
 * &lt;strong&gt;Requires an offset in order to have a common base for comparison&lt;/strong&gt;
 * &lt;/p&gt;
 *
 * @param epochMillis	the timestamp in epoch milliseconds to be checked
 * @param zoneOffset	the offset to be used as base of the comparison
 * @return &lt;code&gt;true&lt;/code&gt; if the dates of the parameter and today are equal,
 *         otherwise &lt;code&gt;false&lt;/code&gt;
 */
public static boolean isToday(long epochMillis, ZoneOffset zoneOffset) {
	// extract the date part from the parameter with respect to the given offset
	LocalDate datePassed = Instant.ofEpochMilli(epochMillis)
								.atOffset(zoneOffset)
								.toLocalDate();
	// then extract the date part of &quot;now&quot; with respect to the given offset
	LocalDate today = Instant.now()
								.atOffset(zoneOffset)
								.toLocalDate();
	// then return the result of an equality check
	return datePassed.equals(today);
}

and then just call it like

boolean isNextReminderToday = isToday(nextReminder, ZoneOffset.systemDefault());

which would use the time offset of the system. Maybe, ZoneOffset.UTC could be a smart choice, too.

答案2

得分: 2

The answer by deHaar is correct. However, I felt to write this one because in this case, using the Zone ID (instead of Zone Offset) makes the code a bit simpler and also easier to understand.

import java.time.Instant;
import java.time.LocalDate;
import java.time.ZoneId;

public class Main {
    public static void main(String[] args) {
        // A test data
        long nextReminder = 1597754387710L;

        // Your time-zone e.g. Europe/London
        ZoneId zoneId = ZoneId.of("Europe/London");

        // Next reminder date
        Instant instant = Instant.ofEpochMilli(nextReminder);
        LocalDate nextReminderDate = instant.atZone(zoneId).toLocalDate();

        // Today at the time-zone of Europe/London
        LocalDate today = LocalDate.now(zoneId);

        if (today.equals(nextReminderDate)) {
            System.out.println("The next reminder day is today");
        }
    }
}

**Output:**

The next reminder day is today
英文:

The answer by deHaar is correct. However, I felt to write this one because in this case, using the Zone ID (instead of Zone Offset) makes the code a bit simpler and also easier to understand.

import java.time.Instant;
import java.time.LocalDate;
import java.time.ZoneId;

public class Main {
	public static void main(String[] args) {
		// A test data
		long nextReminder = 1597754387710L;

		// Your time-zone e.g. Europe/London
		ZoneId zoneId = ZoneId.of(&quot;Europe/London&quot;);

		// Next reminder date
		Instant instant = Instant.ofEpochMilli(nextReminder);
		LocalDate nextReminderDate = instant.atZone(zoneId).toLocalDate();

		// Today at the time-zone of Europe/London
		LocalDate today = LocalDate.now(zoneId);

		if (today.equals(nextReminderDate)) {
			System.out.println(&quot;The next reminder day is today&quot;);
		}
	}
}

Output:

The next reminder day is today

答案3

得分: 1

使用 apache commons 的 DateUtils.isToday(nextReminder)

使用你自己的方法。

private static final long MILLIS_PER_DAY = 86400000;

public static boolean isToday(long timestamp) {
   long now =  System.currentTimeMillis();
   long today = now.getTime() / MILLIS_PER_DAY;
   long expectedDay = timestamp / MILLIS_PER_DAY;
   return today == expectedDay;
}

注意:在处理日期/时间时考虑使用 UTC。

英文:

Using apache commons DateUtils.isToday(nextReminder)

Using your own method.

private static final long MILLIS_PER_DAY = 86400000;

public static boolean isToday(long timestamp) {
   long now =  System.currentTimeMillis();
   long today = now.getTime() / MILLIS_PER_DAY;
   long expectedDay = timestamp / MILLIS_PER_DAY;
   return today == expectedDay;
}

Note: Consider using UTC when working with date/time.

huangapple
  • 本文由 发表于 2020年8月18日 20:13:23
  • 转载请务必保留本文链接:https://go.coder-hub.com/63468352.html
匿名

发表评论

匿名网友

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

确定