如何仅根据提供的小时计算Java中经过的时间

发布于 2024-10-04 20:39:30 字数 484 浏览 5 评论 0原文

这有两个部分:首先计算开始日期。然后计算经过的时间。对于第二部分,我在这里找到了一些很好的建议: Calculate elapsed time in Java / Groovy< /a>

然而,第一部分对我来说是个问题。它的工作原理如下: 用户指定时间跨度从小时值(00 到 23)。我没有任何类型的开始日期/时间对象 - 只是一个整数小时。由此我需要计算开始日期(然后是经过的时间)。

如果开始时间大于当前时间,则为前一天。然而,为了从中获得实际的开始日期,我需要考虑月份和年份的边界以及闰年和夏令时变化等因素。肯定已经有人解决了这样的问题。 (我相信这可能相当复杂。)是否有一个经过验证的解决方案可以让我计算从一天中的给定时间(00 到 24)到现在实际经过了多少时间(以秒为单位)? (开始时间将始终假定为整点。)

There are two parts to this: first compute the start date. Then compute the elapsed time. For the second part, I found some good advice here: Calculate elapsed time in Java / Groovy

However, the first part is a problem for me. Here's how it works:
The user indicates that the time span extends from an hour value (00 to 23). I do not have a starting date/time object of any sort - just an integer hour. From that I need to figure the start date (and then the elapsed time).

If the start hour is greater than the now hour, it was the prior day. In order to get an actual start date from that however, I need to potentially consider month and year boundaries as well as things like leap years and daylight savings time changes. Surely someone has solved a problem like this already. (I believe it can be quite complex.) Is there a proven solution that will let me compute how much time (in seconds) has actually elapsed from the given hour of the day (00 to 24) to now? (The start time will always be assumed to be on the hour.)

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

等风也等你 2024-10-11 20:39:31

首先,我建议使用 Joda Time API。在我看来,它是 Java 可用的最佳日期/时间 API。

接下来,您需要弄清楚在各种极端情况下要做什么。特别是,假设用户输入“1”并且您即将进入夏令时过渡。凌晨 1 点可能发生了两次(如果时间因为从 DST 向后过渡而变为 1:58、1:59、1:00、1:01),或者没有发生完全没有(如果由于转换为 DST 而时间变为 12:58、12:59、2:00)。您需要弄清楚在每种情况下该怎么做 - 请记住,这也意味着要了解时区。

一旦你解决了这个问题,它可能不会太难。使用 Joda Time,您可以使用 withHourOfDay 方法从一个时间转到另一个时间,并设置时间的一个组成部分 - 同样,如果需要,也有简单的 API 用于添加或减去一天。然后,您可以非常轻松地计算出两个 DateTime 值之间的时间 - 同样,Joda Time 提供了您所需的一切。

下面是一个示例,它没有尝试对 DST 转换执行任何操作,但它是一个很好的起点:

import org.joda.time.*;

public class Test
{
    public static void main(String[] args)
    {
        // Defaults to current time and time zone
        DateTime now = new DateTime();
        int hour = Integer.parseInt(args[0]);

        DateTime then = now
            .withHourOfDay(hour)
            .withMinuteOfHour(0)
            .withSecondOfMinute(0);
        if (then.isAfter(now))
        {
            then = then.minusDays(1);
        }
        Period period = new Period(then, now, PeriodType.seconds());

        System.out.println("Difference in seconds: " + period.getSeconds());
    }
}

Firstly, I'd suggest using the Joda Time API. It's the best date/time API available for Java, in my opinion.

Next you need to work out exactly what to do in various corner cases. In particular, suppose the user enters "1" and you're near a daylight saving transition. It's possible that 1am happened twice (if the the time went 1:58, 1:59, 1:00, 1:01 because of a transition back away from DST) or that it didn't happen at all (if the time went 12:58, 12:59, 2:00 because of a transition forward into DST). You need to work out what to do in each of those situations - and bear in mind that this means knowing the time zone too.

Once you've worked that out, it may not be too hard. With Joda Time you can use withHourOfDay method to get from one time to another having set one component of the time - and likewise there are simple APIs for adding or subtracting a day, if you need to. You can then work out the time between two DateTime values very easily - again, Joda Time provides everything you need.

Here's an example which doesn't try to do anything with DST transitions, but it's a good starting point:

import org.joda.time.*;

public class Test
{
    public static void main(String[] args)
    {
        // Defaults to current time and time zone
        DateTime now = new DateTime();
        int hour = Integer.parseInt(args[0]);

        DateTime then = now
            .withHourOfDay(hour)
            .withMinuteOfHour(0)
            .withSecondOfMinute(0);
        if (then.isAfter(now))
        {
            then = then.minusDays(1);
        }
        Period period = new Period(then, now, PeriodType.seconds());

        System.out.println("Difference in seconds: " + period.getSeconds());
    }
}
公布 2024-10-11 20:39:31

java.time

接受的答案提供了使用 Joda-Time API 的解决方案,这可能是最好的第 3 方日期时间 API当时在Java中。 2014 年 3 月,现代日期时间 API 作为 Java 8 标准库的一部分发布。请注意 Joda-Time 主页上的以下消息:

Joda-Time 是 Java 事实上的标准日期和时间库
Java SE 8 之前的版本。现在要求用户迁移到 java.time
(JSR-310)。

使用现代日期时间 API java.time 的解决方案

import java.time.LocalDate;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.time.temporal.ChronoUnit;

class Main {
    public static void main(String[] args) {
        // A sample hour indicated by the user
        int hour = 16;

        // Replace the ZoneId with the applicable one
        ZoneId zone = ZoneId.of("America/New_York");
        ZonedDateTime then = LocalDate.now(zone)
                                      .atStartOfDay(zone)
                                      .withHour(hour);

        ZonedDateTime now = ZonedDateTime.now(zone);
        System.out.println(now);

        if (then.isAfter(now))
            then = then.minusDays(1).withHour(hour);

        long seconds = ChronoUnit.SECONDS.between(then, now);
        System.out.println(seconds);
    }
}

示例运行的输出

2023-01-08T09:31:28.040819-05:00[America/New_York]
63088

在线演示

跟踪:日期时间

java.time

The accepted answer has provided a solution using Joda-Time API which was probably the best 3rd party date-time API in Java at that time. In Mar 2014, the modern date-time API was released as part of the Java 8 standard library. Notice the following message on the Home Page of Joda-Time:

Joda-Time is the de facto standard date and time library for Java
prior to Java SE 8. Users are now asked to migrate to java.time
(JSR-310).

Solution using java.time, the modern date-time API:

import java.time.LocalDate;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.time.temporal.ChronoUnit;

class Main {
    public static void main(String[] args) {
        // A sample hour indicated by the user
        int hour = 16;

        // Replace the ZoneId with the applicable one
        ZoneId zone = ZoneId.of("America/New_York");
        ZonedDateTime then = LocalDate.now(zone)
                                      .atStartOfDay(zone)
                                      .withHour(hour);

        ZonedDateTime now = ZonedDateTime.now(zone);
        System.out.println(now);

        if (then.isAfter(now))
            then = then.minusDays(1).withHour(hour);

        long seconds = ChronoUnit.SECONDS.between(then, now);
        System.out.println(seconds);
    }
}

Output from a sample run:

2023-01-08T09:31:28.040819-05:00[America/New_York]
63088

ONLINE DEMO

Learn more about the modern Date-Time API from Trail: Date Time.

耳根太软 2024-10-11 20:39:31

假设 startHour 由用户指定(假设在 0-23 范围内)。现在你可以从这个开始:

import java.util.Calendar;
import static java.util.Calendar.*;
...
Calendar start = Calendar.getInstance();
if (start.get(HOUR_OF_DAY) < startHour) {
start.add(DAY_OF_MONTH, -1);

Let's say startHour is given by the user (assume, that's in the 0-23 range). Now you may start with this:

import java.util.Calendar;
import static java.util.Calendar.*;
...
Calendar start = Calendar.getInstance();
if (start.get(HOUR_OF_DAY) < startHour) {
start.add(DAY_OF_MONTH, -1);
数理化全能战士 2024-10-11 20:39:31

使用 Joda-Time 类。你可以这样做:

DateTime now = new DateTime();
DateTime start;
int startHour = getStartHour();// user's choice
int nowHour = now.getHourOfDay();
if (nowHour < startHour) {
  start = now.minusHours(24 - startHour + nowHour);
} else {
  start = now.minusHours(nowHour - startHour);
}

Use Joda-Time classes. You can do something like this:

DateTime now = new DateTime();
DateTime start;
int startHour = getStartHour();// user's choice
int nowHour = now.getHourOfDay();
if (nowHour < startHour) {
  start = now.minusHours(24 - startHour + nowHour);
} else {
  start = now.minusHours(nowHour - startHour);
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文