1

It was discussed too many times, I know, but I can't get why the milliseconds generated by mine:

System.currentTimeMillis();

Or by:

Calendar.getInstance(TimeZone.getTimeZone("UTC")).getTimeInMillis()

Are not equal to what I see on www.epochconverter.com?

What I need is to merely generate a String of concrete format, but I've found out the milliseconds aren't right.

Just in case here is how I do it:

private static final String DATE_PATTERN = "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'";

public static String getCurrentTimestamp() {
        long time = System.currentTimeMillis();
        SimpleDateFormat sdf = new SimpleDateFormat(DATE_PATTERN);
        String lastModifiedTime = sdf.format(time);
        Logger.logVerbose(TAG, "Generated timestamp is " + lastModifiedTime);
        return lastModifiedTime;
    }

What I finally get is just a local time, but I need the only time which is pure UTC without conjunction with my timezone.

I've even checked it with SQLite (using the SELECT strftime('%s',timestring);) and got the correct milliseconds. Why then I got it incorrectly generated by those two statements I posted above? Thanks a lot in advance.

4

2 回答 2

1

需要考虑的三件事

  • Java 不支持带闰秒的 UTC,只支持 GMT。这是因为操作系统不支持它。
  • 除非您从卫星同步设备上获得时间,否则您的毫秒数将不准确。
  • 您不能在完全相同的时间运行该命令,因此它们有时会有所不同。

但更重要的是,如果您不设置 tiemzone,它将使用默认时区。

    SimpleDateFormat sdf = new SimpleDateFormat(DATE_PATTERN);
    // no time zone set so the default is used.
    String lastModifiedTime = sdf.format(time);

相反,您应该添加

    sdf.setTimeZone(TimeZone.getTimeZone("GMT"));

在格式中添加 a'Z'只会更改时区,而不是添加'T'到格式中,它只是您添加的一个字母。

于 2013-10-02T14:40:27.197 回答
0

如果您希望日期格式在 UTC 区域中格式化时间,请使用

sdf.setTimeZone(TimeZone.getTimeZone("UTC"));
于 2013-10-02T14:41:38.080 回答