-1

I want to convert timezone from GMT to local timezone based on the device,s location. I have tried various method but not getting the desired result. I know there are lot of solution over the net but i am stuck here.So how can i dot that?I have a GMT timezone format like : 2019-04-10T08:20:25Z

This is the code i have tried so far:

 SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy:MM:dd'T'HH:mm:ss'Z'");
    simpleDateFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
    try {
        Date myDate = simpleDateFormat.parse(onlyDate);
        android.util.Log.v("Df", String.valueOf(myDate));
    } catch (ParseException e) {
        e.printStackTrace();
    }

Here onlyDate is the GMT timezone

Dr Mido
  • 2,414
  • 4
  • 32
  • 72
  • As an aside consider throwing away the long outmoded and notoriously troublesome `SimpleDateFormat` and friends, and adding [ThreeTenABP](https://github.com/JakeWharton/ThreeTenABP) to your Android project in order to use `java.time`, the modern Java date and time API. It is so much nicer to work with. – Ole V.V. Apr 10 '19 at 14:20

2 Answers2

0

Use locale:

  override fun formatDate(date: Date?, dateFormat: String, locale: Locale?): String {
    if (date != null) {
        val localeToUse: Locale
        if (locale != null) {
            localeToUse = Locale.getDefault()
        } else {
            localeToUse = Locale.UK
        }
        try {
            val targetFormat = SimpleDateFormat(dateFormat, localeToUse)
            return targetFormat.format(date).toString()
        } catch (ignore: Exception) {
            // Empty
        }
    }

    return ""
}

Java

   String formatDate(Date date, String dateFormat, Locale locale){
    if (date != null) {
        Locale localeToUse;
        if (locale != null) {
            localeToUse = Locale.getDefault();
        } else {
            localeToUse = Locale.UK;
        }
        try {
            SimpleDateFormat targetFormat = new SimpleDateFormat(dateFormat, localeToUse);
            return targetFormat.format(date);
        } catch (Exception ignore) {
            // Empty
        }
    }

    return "";
}
Antonis Radz
  • 3,036
  • 1
  • 16
  • 34
0

this worked for me:

 SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'");
            formatter.setTimeZone(TimeZone.getTimeZone("UTC"));
            Date value = null;
            try {
                value = formatter.parse(onlyDate);
                SimpleDateFormat dateFormatter = new SimpleDateFormat("dd-MMM-yyyy h:mm:ss a");
                dateFormatter.setTimeZone(TimeZone.getDefault());
               ourDate = dateFormatter.format(value);
                android.util.Log.v("lh", ourDate);

            } catch (ParseException e) {
                e.printStackTrace();
            }