我试过:
TimeZone.getDefault();
我试过:
Calendar mCalendar = new GregorianCalendar();
TimeZone mTimeZone = mCalendar.getTimeZone();
我试过:
Calendar c = Calendar.getInstance();
mTimeZone = c.getTimeZone();
无论我尝试什么...它都会给我一个默认值 0
和 GMT
。我的应用程序似乎无法获取时区(它应该显示为 -4
或 ET
,即美国东部时区)
奇怪的是...我的时钟在我的手机上显示正确的时间。 在我的 Android 设备的设置中选中了“使用自动时区”。
那么,为什么我无法在我的应用程序中获取本地时间? Android 时钟怎么能做到这一点而我却不行?
我已经上网查了,似乎找不到任何东西。至少有一种方法可以与时钟应用程序同步并接收它的时间来显示在我的应用程序上吗?有什么方法可以在我的应用程序上获取正确的时间?
最佳答案
System.getMilliseconds() 返回自纪元以来的时间,仅在使用 GMT 的地区用作当前时间。 (只要你使用的不是自己的转换) 要获取自纪元以来以毫秒为单位的本地时间,您可以使用此函数:
// Kotlin
fun getLocalTime(): Long
{
val currentDate = Calendar.getInstance()
return currentDate.timeInMillis + TimeZone.getDefault().getOffset(currentDate.timeInMillis)
}
在 Java 中可能看起来像这样:
// Java
static long getLocalTime()
{
Calendar currentDate = Calendar.getInstance();
return currentDate.getTimeInMillis() + TimeZone.getDefault().getOffset(currentDate.getTimeInMillis());
}
该函数获取自纪元以来的时间,并向其添加手机本地时区的时区偏移量。
关于android - 在 Android 上获取本地时间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45538413/