【发布时间】:2018-02-10 12:29:50
【问题描述】:
我正在尝试将 UTC 转换为本地时间,
下面是我正在使用的代码,
public static String utcToLocalDateFormat(String dateString) {
Log.i("DateFormat", "utcToLocal:Before===>" + dateString);
String formattedDate = null;
if (dateString != null) {
DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
dateFormat.setTimeZone(TimeZone.getDefault());
Date date = null;
try {
Log.i("DateFormat", "getTimeZone===>" +dateFormat.getTimeZone());
date = dateFormat.parse(dateString);
System.out.println(date);
} catch (ParseException e) {
e.printStackTrace();
}
formattedDate = dateFormat.format(date);
Log.i("DateFormat", "utcToLocal:After===>" + formattedDate);
}
return formattedDate;
}
但问题是时区转换时间前后相同。它没有将UTC转换为本地时间。 任何帮助表示赞赏。
以下是我的输入: 1)2017-08-31 20:40:59 2)2017-09-01 11:16:24.024
以下是输出: 1)2017-08-31 20:40:59 2)2017-09-01 11:16:24
【问题讨论】:
-
您能否提供一些输入和输出(预期与您得到的)?
-
你的
dateFormat将输入解析为本地TZ可以吗? -
在您的日期格式模式中,您没有将在哪个时区传递给您的方法的信息。所以字符串被解析,因为它已经在默认时区。
-
在解析前将dateFormat的时区设置为UTC,以获得正确的UTC时间。然后在格式化之前将其设置为您当地的时区。
-
类似的问题已经被问过很多次了。我想知道您是否可以通过例如Java Convert GMT/UTC to Local time doesn't work as expected 或Java: How do you convert a UTC timestamp to local time? 更快地找到答案。通过发布您自己的问题表示感谢。
标签: java android date timezone simpledateformat