加上GMT时区后显示时间:安卓

问题描述 投票:1回答:2

我工作在一个应用程序中,我要显示通知的时间。我可以显示通知的时间,但不能添加时区了。我现在的位置是巴基斯坦和我想补充GMT + 5:00我的代码附

String currentDateTimeString = DateFormat.getTimeInstance().format(notif.At);
textViewTime.setText(currentDateTimeString);

在此代码,notif.At是日期时间变量。我还附上我的应用程序的截图,我要问你,如何在notif.At添加区值。谢谢!

android
2个回答
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.AtDateobject,它实际上是一个相同的问题:

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年3月31日18点45分28秒GMT + 08:00


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"));
© www.soinside.com 2019 - 2024. All rights reserved.