显示错误的时差

时间:2016-05-11 12:14:14

标签: java date time calendar

我尝试了很多方法来显示两次之间的差异,但我无法找到解决方案:

long strt = System.currentTimeMillis();//1462968291733
Thread.sleep(5000);
long end = System.currentTimeMillis();//1462968296733

long diff = end - strt;

Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(diff);
TimeZone timeZone = TimeZone.getTimeZone("IST");
calendar.setTimeZone(java.util.TimeZone.getTimeZone("UTC"));

System.out.println(calendar.getTime());//05:30:05

打印输出错误:

  

Thu Jan 01 05:30:05 IST 1970

输出应为

  

Thu Jan 01 00:00:05 IST 1970

3 个答案:

答案 0 :(得分:3)

您对时区感到困惑。请尝试以下方法:

long strt = System.currentTimeMillis();// 1462968291733
    Thread.sleep(5000);
    long end = System.currentTimeMillis();// 1462968296733

    long diff = end - strt;


    Calendar calendar = Calendar.getInstance();
    calendar.setTimeInMillis(diff);
    TimeZone cutsomTimeZone = TimeZone.getTimeZone("IST");

     DateFormat formatter = new SimpleDateFormat
                ("EEE MMM dd HH:mm:ss zzz yyyy");
    formatter.setTimeZone(java.util.TimeZone.getTimeZone("UTC"));
    System.out.println(formatter.format(calendar.getTime()));//

    formatter.setTimeZone(cutsomTimeZone);
    System.out.println(formatter.format(calendar.getTime()));

首先,正如javadoc所说,System.currentMillis()返回自1970年1月1日以来 UTC 中的毫秒数,这明显不同于IST。

其次,由Date返回的calendar.getTime()对象不具有时区。使用System.out.println(calendar.getTime())获得的输出使用系统的默认TimeZone,这似乎是IST。

第三,请不要使用Date api,这真的很糟糕。如果可能,请选择java.time

答案 1 :(得分:2)

这是因为默认打印输出使用默认语言环境,在您的情况下为+5:30

您需要在所需的时区格式化输出,例如使用SimpleDateFormat

SimpleDateFormat sdf = new SimpleDateFormat("EEE MMM dd HH:mm:ss zzz yyyy");
sdf.setTimeZone(TimeZone.getTimeZone("UTC"));
System.out.println(sdf.format(calendar.getTime()));

答案 2 :(得分:0)

answer by dejvuthanswer by orris都是正确的。

避免旧的日期时间类。它们已经在Java 8及更高版本的java.time框架中被取代。对于Java 6& 7,大部分功能已由ThreeTen-Backport项目反向移植,并由ThreeTenABP项目进一步适应Android。

根本不需要时区来捕捉经过的时间。

Instant代表UTC时间轴上的一个时刻,分辨率最高为nanoseconds。在Java 8中,当前时刻被捕获的分辨率仅为milliseconds,但Java 9中Clock的新实现将捕获最多纳秒,具体取决于计算机的时钟硬件功能。

request.get('http://google.com', function(error, response, body){
    var $ = cheerio.load(body);
    // Process HTML here
    // How do I save the result from processing with a callback
}

// Or
var parse = function(error, response, body){
    // Process HTML here
    // Assign result to a variable or pass a callback to this function
};
request.get('http://google.com', parse);

A Duration将整个秒的总时间和几分之一秒的时间捕获为纳秒。此值未附加到时间轴。

Instant start = Instant.now();
…
Instant stop = Instant.now();

在生成日期时间值的文本表示时,java.time类使用ISO 8601标准。在两秒半的时间内,您将获得Duration duration = Duration.between( start , stop ); 之类的值,PT2.5S标记开头(期间),P分隔任何年 - 月日从小时 - 分钟 - 秒。这种格式可以防止时钟格式的模糊性,其中T看起来像是午夜过了两分钟的时间。但如果您愿意,可以询问00:00:02.5的数字。

Duration