简体   繁体   English

getTimeinMillis返回负值

[英]getTimeinMillis returns a negative value

I am making an app which can show time left to some date, and an elapsed time after some date. 我正在制作一个可以显示剩余时间和某个日期后经过的时间的应用。 But I endure some difficulties with dates less than 1970 and bigger than 3300. I have found an explanation why it happens. 但是我忍受着一些日期小于1970年且大于3300年的困难。我找到了一个解释为什么会发生这种情况。

The problem is this sentence from getTimeInMillis: the current time as UTC milliseconds from the epoch. 问题是来自getTimeInMillis的这句话:当前时间是从纪元开始的UTC毫秒数。 And, as far as i remember, the epoch started on January 1st 1970 you get a negative number for anything before that. 而且,据我所知,这个时代始于1970年1月1日,在此之前,您得到的任何数字都是负数。

My question is how to solve this problem. 我的问题是如何解决这个问题。 (And yes i have heard about JodaTime, I am not allowed to use this library in this app.) (是的,我听说过JodaTime,不允许在此应用程序中使用此库。)

What default(standard) tools should i use? 我应该使用哪些默认(标准)工具?

Here it is a piece of code that does not work properly. 这是一段无法正常工作的代码。

private void getDateTime()
{
    Date date = new Date();

    timeRemaining = Calendar.getInstance();
    date.setTime(timeRemaining.getTimeInMillis());

    millis = Math.abs(timeRemaining.getTimeInMillis() - targetDate.getTimeInMillis());

    int scnds = (int) (millis / 1000) % 60 ;
    int mnts = (int) ((millis / (1000 * 60)) % 60);
    int hrs = (int) ((millis / (1000 * 60 * 60)) % 24);
    int dys = (int) (millis / (1000 * 60 * 60 * 24));

    resultDate.setText(getString(R.string.formating, dys, hrs, mnts, scnds));
}

You can achieve this by leveraging the Duration and LocalDateTime class(es) introduced in Java 8 -- 您可以利用Java 8引入的DurationLocalDateTime类来实现此目标-

import java.time.Duration;
import java.time.LocalDateTime;

class Main {
  public static void main(String[] args) {
    LocalDateTime fromDateTime = LocalDateTime.of(1914, 9, 10, 0, 0, 0);
    LocalDateTime toDateTime = LocalDateTime.of(2014, 12, 16, 0, 0, 0);
    System.out.println(Duration.between(fromDateTime, toDateTime).toMillis());
  }
}

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

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