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

2 Answers

0
Community On Best Solutions

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();
            }
0
Antonis Radz On

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