当我创建一个新Date对象时,它会初始化为当前时间但在本地时区.如何获得GMT中的当前日期和时间?
我需要将从服务器获得的UTC时间戳转换为本地设备时间.目前我的时间差5小时.例如,当我发布到服务器的帖子时间说5小时前而不是一秒钟前.如何解决这个问题.谢谢
以下是我的代码
long timestamp = cursor.getLong(columnIndex);
CharSequence relTime = DateUtils
.getRelativeTimeSpanString(timestamp * 1000
+ TimeZone.getDefault().getRawOffset(),
System.currentTimeMillis(),
DateUtils.MINUTE_IN_MILLIS);
((TextView) view).setText(relTime);
Run Code Online (Sandbox Code Playgroud) 我一直在StackOverflow Android中获取当前UTC时间, 并且 如何在Java中获取UTC或GMT中的当前日期和时间?
我尝试了两种方法来获取GMT手机的当前时间.我在西班牙,区别是GMT + 2.让我们看一个例子:1º尝试:我创建了一个格式并将其应用于System.currentTimeMillis();
DateFormat dfgmt = new java.text.SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
dfgmt.setTimeZone(TimeZone.getTimeZone("GMT"));
String gmtTime = dfgmt.format(new Date());
//Using System.currentTimeMillis() is the same as new Date()
Date dPhoneTime = dfgmt.parse(gmtTime);
Long phoneTimeUTC = dPhoneTime.getTime();
Run Code Online (Sandbox Code Playgroud)
我需要将那个时间减去另一个时间,这就是为什么我将演员阵容变为Long.
DateFormat df = new java.text.SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
Date arrivalDate = df.parse(item.getArrivalDate());
//the String comes from JSON and is for example:"UTC_arrival":"2011-05-16 18:00:00"
//which already is in UTC format. So the DateFormat doesnt have the GMT paramater as dfgmt
diff = arrival.getTime() - phoneTimeUTC ;
Run Code Online (Sandbox Code Playgroud)
我也试过这个:
Calendar …Run Code Online (Sandbox Code Playgroud) 我注意到System.currentTimeMillis()时间取决于设备.如果我更改设备时钟的时间,此方法将返回不同的答案.
例如:如果现在的实时时间是10:00,并且我将设备上的时钟更改为9:30,那么System.currentTimeMillis()将返回9:30时间(以毫秒为单位).
我也试过这个答案和其他一些答案,但没有找到任何有用的东西.我应该声明我的应用程序主要是脱机工作.有没有办法在没有外部API的情况下获得真实的当前时间(独立于设备)?
我有一个时间戳我想转换为日期.我试过这个时间戳:1336425840.这应该是周一,2012年5月7日21:24:00 GMT,其中GMT是模拟器应该设置的时区.我试过这个:
final Calendar c = Calendar.getInstance();
c.setTimeInMillis(1336425840*1000);
Date d = c.getTime();
Log.i("MyTag", "Hours: " + d.getHours());
Run Code Online (Sandbox Code Playgroud)
结果是:小时:23.
因此,似乎返回的日期是根据GMT + 2计算的,这是我的系统设置的时区.我期望g.hetHours()返回21,因为模拟器的时区似乎设置为GMT.
此外,该时间戳来自于使用mktime读取C中的实际日期,这似乎返回正确的时间戳.但Java似乎指的是不同的时区.我做错了吗?为什么不是周一,2012年5月7日21:24:00 GMT回归?
android ×4
gmt ×2
java ×2
timestamp ×2
timezone ×2
date ×1
date-format ×1
localization ×1
system-clock ×1
time ×1
utc ×1