【问题标题】:Change Date to Local time zone of the device in Java在 Java 中将日期更改为设备的本地时区
【发布时间】:2023-03-16 01:21:01
【问题描述】:

我从数据库中获得了Date 类型的值。这是一个例子Wed Jul 29 13:03:00 GMT +03:00 2020

我有以下方法将其转换为字符串

public static final String VIEW_DATE_FORMAT = "dd MMM yyyy HH:mm";

public static String dateToString(Date date){
    DateFormat dateFormat = new SimpleDateFormat(General.VIEW_DATE_FORMAT , Locale.getDefault());
    if(date == null)
        return "";
    return dateFormat.format(date);
}

我的问题是如何将日期转换为安装应用程序的设备的本地时区? 我希望日期变为Wed Jul 29 2020 16:03:00,但我得到的是Wed Jul 29 2020 13:03:00

【问题讨论】:

    标签: java android


    【解决方案1】:
      public String local_time(String date)
    {
    
        Time time = new Time();
        try {
         date=  date.replace("GMT +","GMT+");
             time.set(new SimpleDateFormat("E MMM dd HH:mm:ss Z yyyy").parse(date).getTime());
        } catch (ParseException e) {
            e.printStackTrace();
        }
        
        String timeString =  time.format("%a %b %d %H:%M:%S  %Z %Y");
       // Log.e("Time string ",""+timeString);
       /* changing time zone */
        time.switchTimezone(Time.getCurrentTimezone());
       // Log.e("Time zone ",""+Time.getCurrentTimezone());
    
       
         timeString = time.format("%a %b %d %H:%M:%S  %Z %Y");
       // Log.e("New time ",""+timeString);
        return timeString;
    }
    

    把它称为String loc_time=local_time("Wed Jul 29 13:03:00 GMT +03:00 2020");

    记得导入 android.text.format.Time : import android.text.format.Time;

    【讨论】:

      【解决方案2】:

      如果您至少使用 API 级别 26,那么您应该使用 ZonedDateTime 类,然后您可以将其转换为 LocalDateTime

      要将Date 对象转换为ZonedDateTime,请参阅Java8 java.util.Date conversion to java.time.ZonedDateTime

      要将ZonedDateTime 转换为LocalDateTime,请参考Convert ZonedDateTime to LocalDateTime at time zone

      【讨论】:

        猜你喜欢
        • 2014-01-28
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-11-03
        • 2021-07-15
        • 1970-01-01
        • 2011-10-09
        相关资源
        最近更新 更多