如何根据设备的位置转换 GMT 时区?

How to convert GMT timezone according to device's Location?

我想根据设备的位置将时区从 GMT 转换为本地时区。我尝试了各种方法但没有得到想要的结果。我知道网上有很多解决方案,但我被卡住了 here.So 我怎么知道呢?我有一个 GMT 时区格式,例如: 2019-04-10T08:20:25Z

这是我目前试过的代码:

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

这里只有Date是GMT时区

使用语言环境:

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

这对我有用:

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