简体   繁体   English

在Java中使用不同的日期作为UNIX时代?

[英]Use different date as UNIX epoch time in Java?

I know that the standard UNIX epoch time is 1/1/70 and I can use this variable to convert current time to UNIX time: 我知道标准的UNIX纪元时间是1/1/70,我可以使用此变量将当前时间转换为UNIX时间:

int time = (int) ((System.currentTimeMillis())/1000); int时间=(int)((System.currentTimeMillis())/ 1000);

(Note: I know it's normally stored as a 64-bit long but I need it to be 32 bit, hence the cast to int). (注意:我知道它通常存储为64位长,但我需要将其存储为32位,因此将其强制转换为int)。

My question is - are there any built-in methods in Java where you can pass in a different date as the "epoch date." 我的问题是-Java中是否有任何内置方法,您可以在其中传递不同的日期作为“时期”。 What I am trying to get is a timestamp in # of seconds since a particular date. 我要获取的是自特定日期以来#秒的时间戳。 Ie I would like to define January 1, 2015 as MY epoch. 即我想将2015年1月1日定义为我的时代。 And then each future date would be # of seconds since 1/1/2015. 那么每个未来的日期将是自2015年1月1日以来的秒数。

If there's no Java library that provides that capability, any ideas on how to do this? 如果没有Java库提供该功能,那么有关如何执行此操作的任何想法? Thanks, Tim 谢谢,蒂姆

There is no library needed, you just have to use maths. 不需要库,您只需要使用数学即可。

static final SimpleDateFormat SDF = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
static final long EPOCH = new Date(2015 - 1900, Calendar.JANUARY, 1).getTime(); // 2015/1/1 in GMT

public static int secondSinceEpoch() {
    return (int) ((System.currentTimeMillis() - EPOCH) / 1000);
}

public static String epochToString(int secsSince2015) {
    return SDF.format(new Date(secsSince2015 * 1000 + EPOCH));
}

public static void main(String... ignored) {
    System.out.println(new Date(EPOCH));
    System.out.println("Epoch is " + epochToString(0));
    System.out.println("Today is " + secondSinceEpoch() + " secs");
    System.out.println("Today is " + secondSinceEpoch() / 86400 + " days");
}

prints 版画

Thu Jan 01 00:00:00 GMT 2015
Epoch is 2015/01/01 00:00:00
Today is -15732850 secs
Today is -182 days

You'd probably have to roll your own time and date methods, which would basically repackage the standard ones while subtracting the correct number of seconds to the epoch to arrive at your new epoch. 您可能必须滚动自己的时间和日期方法,这将基本上重新包装标准方法,同时将相应的秒数减去正确的秒数,以得出新的纪元。

So, maybe something like 所以,也许像

public class MyEpoch {
    public static final Long MY_EPOCH = //number of seconds betweer 1/1/70 and 1/1/2015
    private Date unixEpochDate;
    //etc
    public Long getMyEpoch() {
        return unixEpochDate.getTime() - MY_EPOCH;
    }
}

tl;dr TL;博士

long totalSeconds = Duration.between ( OffsetDateTime.of ( 2015 , 1 , 1 , 0 , 0 , 0 , 0 , ZoneOffset.UTC ) , OffsetDateTime.now ( ZoneOffset.UTC ) ).getSeconds ();

Elapsed time 经过时间

Forget about the epoch reference date . 忘记时代参考日期 What you want is simply elapsed time. 您想要的只是经过的时间。

java.time java.time

The java.time framework is built into Java 8 and later. java.time框架内置于Java 8及更高版本中。 These classes supplant the old troublesome date-time classes such as java.util.Date , .Calendar , & java.text.SimpleDateFormat . 这些类取代了麻烦的旧日期时间类,例如java.util.Date.Calendarjava.text.SimpleDateFormat The Joda-Time team also advises migration to java.time. Joda-Time小组还建议迁移到java.time。

To learn more, see the Oracle Tutorial . 要了解更多信息,请参见Oracle教程 And search Stack Overflow for many examples and explanations. 并在Stack Overflow中搜索许多示例和说明。

Much of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport and further adapted to Android in ThreeTenABP . 多的java.time功能后移植到Java 6和7在ThreeTen-反向移植并且还适于在到Android ThreeTenABP

Time zone 时区

Your question fails to address the crucial issue of time zone. 您的问题未能解决时区这一关键问题。

Since you mentioned Unix-style time, I will assume you intended UTC time zone. 既然您提到了Unix风格的时间,我将假设您打算使用UTC时区。 The Instant class represents a moment on the timeline in UTC with a resolution up to nanosecond. Instant类以UTC表示时间轴上的时刻,分辨率最高为纳秒。 For more flexibility including formatting, use an OffsetDateTime with an assigned offset of UTC instead. 为了获得更大的灵活性,包括设置格式,请使用OffsetDateTime和指定的UTC偏移量。

Duration

The OffsetDateTime class represents a date and time-of-day with an assigned offset-from-UTC. OffsetDateTime类表示具有指定的UTC偏移量的日期和时间。 We can specify the constant ZoneOffset.UTC as the offset value. 我们可以将常量ZoneOffset.UTC指定为偏移值。

The Duration class represents a span of time as a total number of seconds plus a fractional second in nanoseconds. Duration类将Duration跨度表示为总秒数,以秒为单位,以纳秒为单位。 We can get a Duration object from our pair of OffsetDateTime objects. 我们可以从我们的OffsetDateTime对象对中获取一个Duration对象。

Calling Duration::getSeconds gets the total number of seconds in the duration. 调用Duration::getSeconds获取Duration::getSeconds的总秒数。 But note that we may be losing data as any fractional second will naturally be omitted from the resulting number. 但是请注意,我们可能会丢失数据,因为自然会从结果数中忽略任何小数秒。

OffsetDateTime start = OffsetDateTime.of ( 2015 , 1 , 1 , 0 , 0 , 0 , 0 , ZoneOffset.UTC );
OffsetDateTime now = OffsetDateTime.now ( ZoneOffset.UTC );

Duration duration = Duration.between ( start , now );
long totalSeconds = duration.getSeconds ();

Dump to console. 转储到控制台。

System.out.println ( "start: " + start + " | now: " + now + " | duration: " + duration + " | totalSeconds: " + totalSeconds );

start: 2015-01-01T00:00Z | 开始时间:2015-01-01T00:00Z | now: 2016-07-24T04:15:57.345Z | 现在:2016-07-24T04:15:57.345Z | duration: PT13684H15M57.345S | 持续时间:PT13684H15M57.345S | totalSeconds: 49263357 总计秒:49263357

Going the other direction, calculating a date-time from your starting point with a number of seconds, is easy. 换个方向,从您的起点算起几秒钟的日期时间很容易。 Just call plusSeconds . 只需致电plusSeconds

Rather than dirty your code with “magic” numbers and math calculations to get a number of seconds, use the TimeUnit class. 使用TimeUnit类,而不是使用“魔术”数字和数学计算来TimeUnit代码,以获取秒数。

OffsetDateTime start = OffsetDateTime.of ( 2015 , 1 , 1 , 0 , 0 , 0 , 0 , ZoneOffset.UTC );
long seconds = TimeUnit.HOURS.toSeconds ( 7 );  // Let `TimeUnit` class do the math of calculating seconds.
OffsetDateTime stop = start.plusSeconds ( seconds );

2015-01-01T07:00Z 2015-01-01T07:00Z

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM