1

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

warCommander
  • 392
  • 4
  • 19

2 Answers2

1

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

Abra
  • 19,142
  • 7
  • 29
  • 41
0
  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;

Code Demon
  • 1,256
  • 1
  • 9
  • 15