【问题标题】:Find the difference between a Posted UTC timestamp in minutes from the current time查找发布的 UTC 时间戳与当前时间之间的差异(以分钟为单位)
【发布时间】:2017-09-04 17:05:24
【问题描述】:

我正在尝试做的事情:检查事件发生前的分钟数。 (我在中部时间,即 UTC -5 小时)。 我得到的对象是一个 JSON 元素,当我获取字符串时,它看起来像这样:

/日期(1502964420000-0500)/

我应该能够:

//take the departure time and subtract it from the current time. Divide by 60
    timeStamp = timeStamp.substring(6,16);

这给了我 1502964420,我可以使用时间转换器得到:2017 年 8 月 17 日星期四 5:07:00 AM

问题是..如何以相同格式获取当前时间以减去它? (或者如果有更好的方法来做到这一点,我也很乐意接受这个建议)。

【问题讨论】:

标签: java date utc


【解决方案1】:

我建议查看数据类型 ZonedDateTime

有了它,您可以轻松地执行计算和转换,如下所示:

ZonedDateTime startTime = ZonedDateTime.now();
Instant timestamp = startTime.toInstant(); // You can also convert to timestamp
ZonedDateTime endTime = startTime.plusSeconds(30);

Duration duration = Duration.between(startTime, endTime);

if(duration.isNegative()){
  // The end is before the start
}

long secondsBetween = duration.toMillis(); // duration between to seconds

由于您不了解 ZonedDateTime,这里简要概述如何将字符串转换为 ZonedDateTime:

注意:字符串必须是ISO8601 格式!

String example = "2017-08-17T09:14+02:00";
OffsetDateTime offset = OffsetDateTime.parse(example);
ZonedDateTime result = offset.atZoneSameInstant( ZoneId.systemDefault() );

【讨论】:

    【解决方案2】:

    您可以使用Date currentDate = new Date() 然后currentDate.getTime() 来获取当前的Unix 时间(以毫秒为单位),或者使用Calendar 类:Calendar currentDate = Calendar.getInstance()currentDate.getTime().getTime() 来获取当前的Unix 时间(以毫秒为单位)。

    您可以对从 json 解析的日期执行相同操作,然后计算两个值之间的差异。要以分钟为单位,只需将其除以 (60*1000)

    【讨论】:

    • 想法是对的,请不要教年轻人使用陈旧的课程DateCalendar。今天我们已经好多了。我推荐 Instant 类。
    猜你喜欢
    • 1970-01-01
    • 2020-06-08
    • 1970-01-01
    • 2021-11-14
    • 2021-05-14
    • 1970-01-01
    • 2021-01-04
    • 2012-12-10
    • 2012-05-01
    相关资源
    最近更新 更多