简体   繁体   中英

Change Date to Local time zone of the device in Java

I'm getting a value of type Date from the Database. Here is an example Wed Jul 29 13:03:00 GMT +03:00 2020

and I have the following method to convert it to string

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);
}

My Question is how to convert the date to the Local time zone of the device the app is installed on? I want the date to become Wed Jul 29 2020 16:03:00 but I'm getting Wed Jul 29 2020 13:03:00 instead

If you are using at least API level 26 then you should use class ZonedDateTime which you can then convert to a LocalDateTime .

To convert a Date object to ZonedDateTime , refer to Java8 java.util.Date conversion to java.time.ZonedDateTime

To convert ZonedDateTime to LocalDateTime , refer to Convert ZonedDateTime to LocalDateTime at time zone

  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;
}

call it like String loc_time=local_time("Wed Jul 29 13:03:00 GMT +03:00 2020");

remember to import android.text.format.Time: import android.text.format.Time;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM