如何在Java中找到给定时间点所在的年份的第几分钟?

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

How to find minute of the year at a given point of time in java?

问题

如何在Java中找到任意特定时间的年中分钟。

根据以下定义,需要在V2X消息中使用:

MinuteOfTheYear ::= INTEGER(0..527040)
英文:

How to find minute of the year in java at any particular time.

It is required to be used in V2X messages as per the below definition:

MinuteOfTheYear ::= INTEGER (0..527040)

答案1

得分: 4

时间是棘手的。如果没有进一步的细节,这个问题是无法回答的。

让我们来看看这些术语:

如何在特定时间使用Java找到一年中的分钟。

定义"时间"。你是指:宇宙中的某一刻,还是指:挂在墙上的时钟读数?这两者并不相同。

如果我现在拍手,那么我(居住在荷兰)会说现在是下午5点14分。但在那个确切的时刻,纽约的某人会声称现在是上午11点14分。

当你说"时间"时,是更像"当我拍手的时候"还是更像"三月十四日的十一点零五分"?

如何在Java中找到特定时间的一年中的分钟数

这里同样适用 - "一年中的分钟数" 暗示着你想要知道 "年份 X 的第一分钟" 与 "此刻的时间" 之间的差异,其中 X 是与该时间相同的年份。这也涉及到时区问题。

换句话说:如果我们按照时刻来计算,如果我在伦敦的烟火表演之后的5分钟内拍手,答案是"5"。但在纽约的某人在完全相同的时间里仍在等待(几乎)6个小时的新年;他们会用525245来回答你的问题,这是一个完全不同的答案。

我是指挂在墙上的时钟

在这种情况下,你的输入可能是:7月24日星期五,17:15:00,并且你想要的答案是将"新年"定义为同一时区。

不幸的是,这是一个无法回答的问题,除非我们知道我们在地球上的哪个位置。一些时区会调整时间。一些不会。在欧洲,如果你现在问,你必须考虑到三月的某个地方,时钟被向前调整了(还是向后,我永远记不清楚),这会产生60分钟的差异。但在不执行夏时制的地区,从未发生过这种情况。因此:在没有告诉我_在哪里_的情况下,无法回答。

我是指时间点

在这种情况下,你的输入可能是"距离纪元以来的1595603962356毫秒"。在不知道我们生活在地球上的哪个位置的情况下,根本就没有"年初"这个概念,以毫秒为单位的纪元时间也无法定义。再次强调,在哪里 是重要的。

我是指:就是现在!

这归结为前面的情况;你可以通过 System.currentTimeMillis()Instant.now() 获取当前的时间点。

还有... 就在这里!

嗯,"就在这里" 指的是Java代码运行的地方。如果我们在谈论服务器和客户端,可能不正确(客户端可能在其他地方)。

ZoneId.systemDefault() 可以获得服务器标识为"本地时区ID"的时区标识。

请给出代码!

首先,你必须获取一个特定位置的时间点:

// 输入
Instant now = Instant.now();
ZoneId zone = ZoneId.systemDefault();

// 或者使用另一种输入:
Instant now = Instant.ofEpochMilli(1595603962356);
ZoneId zone = ZoneId.of("Europe/Amsterdam");

// 转换为人类可读的格式
ZonedDateTime zdt = now.atZone(zone);

// 获取本年的第一个时间点
ZonedDateTime start = ZonedDateTime.of(zdt.getYear(), 1, 1, 0, 0, 0, 0, zone);

// 计算差异,以分钟为单位
int answer = (int) ChronoUnit.MINUTES.between(start, zdt);

System.out.println(answer);

以下是一个"就在这里,就在现在"的例子:

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

public class RightNowRightHere {
    public static void main(String[] args) {
        Instant now = Instant.now();
        ZoneId zone = ZoneId.systemDefault();
        ZonedDateTime zdt = now.atZone(zone);
        ZonedDateTime start = ZonedDateTime.of(zdt.getYear(), 1, 1, 0, 0, 0, 0, zone);
        int answer = (int) ChronoUnit.MINUTES.between(start, zdt);
        System.out.println(answer);
    }
}

对我来说,输出是 296188

英文:

Time is tricky. This question cannot be answered without further detail.

Let's go through the terms:

> How to find minute of the year in java at a particular time.

Define 'time'. Do you mean: Some instant in the universe, or do you mean: Some readout on a wallclock? These two are not the same.

If I clap my hands right now, then I (living in The Netherlands), would say it is 14 minutes past 5 in the afternoon. But at that exact moment in time, someone in New York would claim that it is 14 minutes past 11 in the morning.

When you say 'time' do you mean more like 'when I clap my hands' or more like '5 past eleven on the 14th of march'?

> How to find minute of the year in java at a particular time.

The same applies here - 'minute of the year' implies you wish to know the difference between 'the very first minute of year X' and 'this moment in time', where X is the same year as said moment in time. This too involves timezones.

Said differently: If we go by moment-in-time, and I clap my hands at 5 minutes past the fireworks in london, the answer is '5'. Except someone in New York, at that exact same time, is still waiting (almost) 6 hours for new years; they'd answer your question with 525245; a wildly different answer.

I meant the wallclock time thing

In that case, your input is something like: Friday, 24th of July, 17:15:00, and you'd want to know the answer by defining 'new years' as being in the same zone.

Unfortunately, this is not an answerable question without knowing where on the planet we are. Some timezones move the clock around. Some do not. In europe, asking right now, you have to take into account that someplace in march, the clocks were moved forward (or was it back, I can never remember), that makes 60 minutes worth of difference. But in locales which don't do daylight savings, that never happened. Therefore: Impossible to answer without telling me WHERE.

I meant the instant-in-time thing

In that case, your input is something like '1595603962356 milliseconds since the epoch'. There is no such thing as 'start of the year' in millis since epoch without knowing where on the planet we live. Again, where is important.

I meant: Right now!

That boils down to the previous case; you'd get the current instant-in-time via System.currentTimeMillis() or Instant.now()

And... Right here!

Ah, well, 'right here' is where the java code runs. If we're talking servers and clients that may not be correct (the client could be elsewhere).

ZoneId.systemDefault() gets you the zone ID as identified by the server as 'the local zone id'.


Code please!

First, you must obtain an instant in time, localized in some location:

// inputs
Instant now = Instant.now();
ZoneId zone = ZoneId.systemDefault();

// alternative inputs:
Instant now = Instant.ofEpochMilli(1595603962356);
ZoneId zone = ZoneId.of("Europe/Amsterdam");

// convert to human style
ZonedDateTime zdt = now.atZone(zone);

// obtain first instant in time in this year
ZonedDateTime start = ZonedDateTime.of(zdt.getYear(), 1, 1, 0, 0, 0, 0, zone);

// find the difference, in minutes
int answer = (int) ChronoUnit.MINUTES.between(start, zdt);

System.out.println(answer);

Here's an example for 'right now, right here':

import java.time.Instant;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.time.temporal.ChronoUnit;
public class RightNowRightHere {
    public static void main(String[] args) {
        Instant now = Instant.now();
        ZoneId zone = ZoneId.systemDefault();
        ZonedDateTime zdt = now.atZone(zone);
        ZonedDateTime start = ZonedDateTime.of(zdt.getYear(), 1, 1, 0, 0, 0, 0, zone);
        int answer = (int) ChronoUnit.MINUTES.between(start, zdt);
        System.out.println(answer);
    }
}

prints 296188 for me.

答案2

得分: 2

细心的 rzwitserloot 的回答 是正确的,并且值得研究。但我怀疑您的用例特定于 UTC,而不是特定的时区。

特定于 UTC

以 UTC 所见的当前时刻进行捕捉。

OffsetDateTime now = OffsetDateTime.now( ZoneOffset.UTC ) ;

提取年份。用于确定该年的第一天。

Year year = Year.of( now.getYear() ) ;
LocalDate ld = year.atDay( 1 ) ;

与时间 00:00:00 以及 UTC(零小时-零分钟-零秒的偏移量)结合,以确定该年的第一时刻。

OffsetDateTime startOfYear = OffsetDateTime.of( ld , LocalTime.MIN , ZoneOffset.UTC ) ;

计算从年初到现在经过的时间。Duration 类表示与时间线无关的时间跨度,其尺度为不附加于日历、小时、分钟、秒以及分数秒的通用 24 天。

Duration d = Duration.between(  startOfYear , now ) ;

提取跨越整个时间段的总分钟数。

long minutes = d.toMinutes() ;

我们可以将代码折叠起来。

long minutes =
        Duration.between(
            OffsetDateTime.of(
                Year.of( now.getYear() ).atDay( 1 ) ,
                LocalTime.MIN ,
                ZoneOffset.UTC
            )
            ,
            now
        )
        .toMinutes()
;
英文:

The thoughtful Answer by rzwitserloot is correct, and worth studying. But I suspect your use-case is specific to UTC rather than a particular time zone.

UTC specifically

Capture the current moment as seen in UTC.

OffsetDateTime now = OffsetDateTime.now( ZoneOffset.UTC ) ;

Extract the year. Use that to determine the first day of year.

Year year = Year.of( now.getYear() ) ;
LocalDate ld = year.atDay( 1 ) ;

Combine with the time 00:00:00 and UTC (offset of zero hours-minutes-seconds) to determine the first moment of the year.

OffsetDateTime startOfYear = OffsetDateTime.of( ld , LocalTime.MIN , ZoneOffset.UTC ) ;

Calculate the time elapsed between the start of year and now. The Duration class represents a span-of-time unattached to the timeline on the scale of generic 24-long days not attached to the calendar, hours, minutes, seconds, and fractional second.

Duration d = Duration.between(  startOfYear , now ) ;

Extract a total number of minutes across the entire span of time.

long minutes = d.toMinutes() ;

We could collapse that code.

long minutes =
        Duration.between(                               // Passing a pair of `OffsetDateTime` objects.
            OffsetDateTime.of(                          // Passing date, time, offset.
                Year.of( now.getYear() ).atDay( 1 ) ,   // Returns a `LocalDate` object.
                LocalTime.MIN ,                         // A constant `LocalTime` object.
                ZoneOffset.UTC                          // A constant `ZoneOffset` object. Represents an offset of zero hours-minutes-seconds.
            )                                           // Returns a `OffsetDateTime` object, the first of our pair of `OffsetDateTime` objects being passed to `Duration.between`. 
            , 
            now                                         // The `OffsetDateTime` object we instantiate above, capturing the current moment. The second of our pair of `OffsetDateTime` objects being passed to `Duration.between`. 
        )                                               // Returns a `Duration` object.
        .toMinutes()                                    // Returns a `long`, the total number of minutes across the entire span-of-time. Not to be confused with `Duration::toMinutesPart`. 
;

答案3

得分: -1

我建议的解决方案是构建两个方法,第一个方法乘以一个数字参数(年份数字,如1),乘以每365天的分钟数(一年):

public static long MinutesOfTheYear(final long year) {
    return (year * 525600l);
    /* 例如,要计算一年中的分钟数,请执行以下操作:
    long year = 1;
    System.out.println( MinutesOfTheYear(year) );
    输出:
    525600l(一年中的分钟数)
     */
}

第二个方法接受一个指定日期的 Calendar 对象作为参数,然后将其转换为相对于指定的年、月和日的分钟数:

public static long MinutesOfTheYear(final java.util.Calendar calendar) {

    int DaysOfTheMonth = 0;

    switch (calendar.get(java.util.Calendar.MONTH) - 1) {
        case 1:
            // (一月)
        case 3:
            // (三月)
        case 5:
            // (五月)
        case 6:
            // (六月)
        case 7:
            // (七月)
        case 8:
            // (八月)
        case 10:
            // (十月)
        case 12:
            // (十二月)
            DaysOfTheMonth = 31;
            break;
        case 2:
            // (二月)28 或 29
            DaysOfTheMonth = 28;
            break;
        case 4:
            // (四月)
        case 9:
            // (九月)
        case 11:
            // (十一月)
            DaysOfTheMonth = 30;
            break;
    }

    return (525600l) + ((DaysOfTheMonth) * 1440l)
            + (calendar.get(java.util.Calendar.DAY_OF_MONTH) * 1440l);

    /* 还可以用于计算特定日期的分钟数(年份加上月和日):
    java.util.Calendar calendar = java.util.Calendar.getInstance();
    
   //** 将所需的日期提供给 Calendar 对象(此类替代了已在 Java 版本 1.1 中废弃的 Date 类): **
   
    calendar.set(year, month, day);
    System.out.println(calendar);
    输出:
    year(525600l)+ month(month * 43800l)+ day(date * 1440l)
    */
}
**祝好运**
英文:

Well, my suggested solution is to build two methods, the first method multiplying by an argument of number (year number like 1) multiplied by the number of minutes every 365 days (one year):

public static long MinutesOfTheYear(final long year) {
return (year * 525600l);
/* For example, to calculate the number of minutes in a year, do the following:
long year = 1;
System.out.println( MinutesOfTheYear(year) );
Output:
525600l (Number of minutes a year)
*/
}

And the second method, which accepts a Calendar object with a specified date as a parameter, and then converts it to minutes relative to the specified year, month, and day:

public static long MinutesOfTheYear(final java.util.Calendar calendar) {
int DaysOfTheMonth = 0;
switch (calendar.get(java.util.Calendar.MONTH) -1) {
case 1:
// (January)
case 3:
// (March)
case 5:
// (May)
case 6:
// (June)
case 7:
// (July)
case 8:
// (August)
case 10:
// (October)
case 12:
// (December)
DaysOfTheMonth = 31;
break;
case 2:
// (February) 28 or 29
DaysOfTheMonth = 28;
break;
case 4:
// (April)
case 9:
// (September)
case 11:
// (November)
DaysOfTheMonth = 30;
break;
}
return ( 525600l ) + ( ( DaysOfTheMonth ) * 1440l )
+ ( calendar.get(java.util.Calendar.DAY_OF_MONTH) * 1440l );
/* Also to calculate the number of minutes of a particular date (year plus month and day):
java.util.Calendar calendar = java.util.Calendar.getInstance();
//** Give the desired date to the Calendar object (this class replaces the Date class, which became obsolete in Java version 1.1): **
calendar.set( year, month, day );
System.out.println( calendar );
Output:
year (525600l) + month (month * 43800l) + day (date * 1440l)
*/
}

Good luck!

huangapple
  • 本文由 发表于 2020年7月24日 23:08:52
  • 转载请务必保留本文链接:https://go.coder-hub.com/63076386.html
匿名

发表评论

匿名网友

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

确定