System.currentTimeMillis() returns 日期错误
System.currentTimeMillis() returns wrong date
我正在尝试将当前时间保存到共享首选项中,但由于某种原因,在遥远的未来 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();
}
所以基本上在调试时我注意到 currentTime
是 1436374427923
也就是 Tue, 23 Nov 47486 00:38:43 GMT
...
您的值是毫秒(如 currentTimeMillis
),您将其视为秒。
将它除以一千(即,将其转换为秒),您会得到更合理的值 Wed, 08 Jul 2015 16:53:47 GMT
。
System.currentTimeMillis()
returns 自 1970-01-01 00:00:00 UTC 以来的毫秒数。
UTC 是世界通用的时间标准。它也被认为是 GMT(格林威治标准时间)-不完全一样-。
所以如果你在不同的时区,那么你应该考虑到这一点。
如果您想从当前毫秒数获取格式化日期,那么您可以这样做:
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();
}
我正在尝试将当前时间保存到共享首选项中,但由于某种原因,在遥远的未来 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();
}
所以基本上在调试时我注意到 currentTime
是 1436374427923
也就是 Tue, 23 Nov 47486 00:38:43 GMT
...
您的值是毫秒(如 currentTimeMillis
),您将其视为秒。
将它除以一千(即,将其转换为秒),您会得到更合理的值 Wed, 08 Jul 2015 16:53:47 GMT
。
System.currentTimeMillis()returns 自 1970-01-01 00:00:00 UTC 以来的毫秒数。
UTC 是世界通用的时间标准。它也被认为是 GMT(格林威治标准时间)-不完全一样-。
所以如果你在不同的时区,那么你应该考虑到这一点。
如果您想从当前毫秒数获取格式化日期,那么您可以这样做:
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();
}