我正在开发一个我希望显示通知时间的应用程序。 我可以显示通知时间但不能在其中添加时区。 我目前的位置是巴基斯坦,我想加GMT + 5:00 我的代码已附上
String currentDateTimeString = DateFormat.getTimeInstance().format(notif.At);
textViewTime.setText(currentDateTimeString);
在此代码中,notif.At是dateTime变量。我还附上了我的应用程序的截图,我想问你,如何在notif.At中添加timeZone值。谢谢!
答案 0 :(得分:1)
为了解决国际化问题,你用时区标记时间,我理解,对吗?
如果是这样,我认为将您的日期转换为UTC日期会更好。当您更改为其他时区时,只需将此UTC日期转换为本地。
public static Date localToUtc(Date localDate) {
return new Date(localDate.getTime()-TimeZone.getDefault().getOffset(localDate.getTime()));
}
public static Date utcToLocal(Date utcDate) {
return new Date(utcDate.getTime()+TimeZone.getDefault().getOffset(utcDate.getTime()));
}
如果您的notif.At
是Date
对象,实际上是同一个问题:
TimeZone tz = TimeZone.getDefault();
Date date = new Date();
final String format = "yyyy-MM-dd HH:mm:ss";
SimpleDateFormat sdf = new SimpleDateFormat(format, Locale.US);
String result = sdf.format(date);
Log.d("Date ", "date: " + result + " " + tz.getDisplayName(false, TimeZone.SHORT));
打印:
日期:2015-03-31 18:45:28 GMT + 08:00
答案 1 :(得分:1)
您可以尝试java.time api;
Instant date = Instant.ofEpochMilli(1549362600000l);
LocalDateTime utc = LocalDateTime.ofInstant(date, ZoneOffset.UTC);
LocalDateTime pst = LocalDateTime.ofInstant(date, ZoneOffset.of("+05:00"));
LocalDateTime is = LocalDateTime.ofInstant(date, ZoneOffset.of("+05:30"));