我想根据设备的位置将时区从GMT转换为本地时区。我尝试了各种方法,但没有得到理想的结果。我知道网上有很多解决方案,但我被困在这里,那么我该如何点呢?我有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();
}
只有日期是格林尼治标准时间(GMT)时区
答案 0 :(得分:0)
使用语言环境:
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 "";
}
答案 1 :(得分:0)
这对我有用:
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();
}