在Android中获得UTC/GMT的日期



我想在某个国家/地区显示时间,而时区为GMT 4。

private void loadWeather(){
    TimeZone tz = TimeZone.getTimeZone("GMT+0400");
    Calendar cal = Calendar.getInstance(tz);
    Date date = cal.getTime();
    DateFormat df = DateFormat.getDateTimeInstance(DateFormat.SHORT,DateFormat.SHORT, Locale.getDefault());
    String myDate = df.format(date);
    tv_time.setText(myDate);
}

我已经尝试过,但是它给了我我的时间,而不是另一个

问题是您仅在Calendar上指定时区 - 仅用于及时获得当前的速度,而不是取决于时区。您需要在格式上指定它,以便在创建该瞬间的适当文本表示时应用它:

private void loadWeather() {
    Date date = new Date(); // This is enough; it uses the current instant.
    DateFormat df = DateFormat.getDateTimeInstance(
        DateFormat.SHORT, DateFormat.SHORT, Locale.getDefault());
    df.setTimeZone(TimeZone.getTimeZone("GMT+0400"));
    String myDate = df.format(date);
    tv_time.setText(myDate);
}

或更多的内联:

private void loadWeather() {
    DateFormat df = DateFormat.getDateTimeInstance(
        DateFormat.SHORT, DateFormat.SHORT, Locale.getDefault());
    df.setTimeZone(TimeZone.getTimeZone("GMT+0400"));
    tv_time.setText(df.format(new Date()));
}

(这是假设您确实需要使用当前语言环境的短期/时间格式。)

我想在某个国家/地区显示时间,而时区为GMT 4。

GMT 4是不是时区。时区表示为 age/city ,例如欧洲/伦敦。检查TZ数据库时区的列表以获取更多示例。GMT 4表示时区偏移即提前4个小时,因此,为了获得UTC的等价日期,必须从GMT 4的日期时间开始减去4小时。

GMT 4不是表示时区偏移量的标准方法

标准格式是+/-HH:mm:ssZ,它是指+00:00偏移。在大多数情况下,您会看到+/-HH:mm,例如+06:00。检查此Wikipedia链接以了解有关它的更多信息。

java.Time

java.util日期时间API及其相应的解析/格式化类型SimpleDateFormat已过时并且容易出错。2014年3月,现代日期API作为 Java 8标准库发布,该库取代了传统的日期时间API,从那时起,强烈建议您切换到java.time,现代日期(现代日期)-Time API。

使用java.time

解决方案

用时区表示日期时间 offset ,Java 8 标准库提供java.time.OffsetDateTime

演示:

import java.time.OffsetDateTime;
import java.time.ZoneOffset;
class Main {
    public static void main(String[] args) {
        OffsetDateTime now = OffsetDateTime.now(ZoneOffset.of("+04:00"));
        System.out.println(now);
        // The corresponding date-time at UTC
        System.out.println(now.toInstant());
        // Alternatively
        System.out.println(now.withOffsetSameInstant(ZoneOffset.UTC));
    }
}

示例运行的输出

2023-02-04T14:08:58.657721+04:00
2023-02-04T10:08:58.657721Z
2023-02-04T10:08:58.657721Z

在线演示

trail:日期时间

了解有关现代日期API的更多信息

使用下面的 SimpleDateFormat并将TimeZone设置为SimpleDateFormat对象...我认为,您会遇到问题。

    Calendar calendar = Calendar.getInstance();
    SimpleDateFormat dateFormatGmt = new SimpleDateFormat("dd:MM:yyyy HH:mm:ss");
    dateFormatGmt.setTimeZone(TimeZone.getTimeZone("GMT+0400"));
    String date = dateFormatGmt.format(calendar.getTime());

最新更新