【问题标题】:System.currentTimeMillis() returns wrong dateSystem.currentTimeMillis() 返回错误的日期
【发布时间】:2015-09-27 01:23:06
【问题描述】:

我正在尝试将当前时间保存到共享偏好中,但由于某种原因,在遥远的未来一年 47486 中,当前时间是一个荒谬的数量。

我已经检查了设备本身的日期设置并且日期是正确的,我在任何地方都找不到这样的问题。我希望这里有人可以帮助我。

这就是问题所在:

public static void setLastSyncSucceeded(final Context context) {
     SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(context);
     long currentTime = System.currentTimeMillis();
     sp.edit().putLong(PREF_LAST_SYNC_SUCCEEDED, currentTime).commit();
}

所以基本上在我调试的时候我注意到currentTime1436374427923 这是Tue, 23 Nov 47486 00:38:43 GMT...

【问题讨论】:

标签: android time timestamp sharedpreferences unix-timestamp


【解决方案1】:

您拥有的值是毫秒(如currentTimeMillis),您将其视为秒。

将其除以一千(即,将其转换为秒),您将得到更合理的 Wed, 08 Jul 2015 16:53:47 GMT 值。

【讨论】:

  • 谢谢你,我没有注意到我用来转换时间的网站是从秒而不是毫秒转换的问题
【解决方案2】:

System.currentTimeMillis()
返回自 1970-01-01 00:00:00 UTC 以来的毫秒数。

UTC 是世界上通用的时间标准。它也被认为是 GMT(格林威治标准时间)-不完全一样-。

所以如果你在不同的时区,那么你应该考虑到这一点。

【讨论】:

  • 问题是关于47486 的年份,而不是时区。
  • @BasilBourque 您是否尝试过将 1436374427923 转换为 Date 它是有效的日期和时间。显然 47486 是操作的错误。我们不知道他是如何试图转变为日期的。
【解决方案3】:

如果您想从当前毫秒获取格式化日期,那么您可以执行以下操作:

long yourmilliseconds = System.currentTimeMillis();
SimpleDateFormat sdf = new SimpleDateFormat("MMM dd yyyy HH:mm"); //Play with the parameters to get different results
Date resultdate = new Date(yourmilliseconds);
String formattedActualDate = sdf.format(resultdate);

或者很容易:

SimpleDateFormat sdf = new SimpleDateFormat("MMM dd yyyy HH:mm");
String formattedActualDate = sdf.format(new Date());

最后:

public static void setLastSyncSucceeded(final Context context) {
     SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(context);
     long currentTime = System.currentTimeMillis();
     sp.edit().putLong(PREF_LAST_SYNC_SUCCEEDED, formattedActualDate).commit();
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-11-08
    • 2013-09-04
    • 2018-04-05
    • 2016-09-26
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多