【发布时间】:2020-01-19 12:23:58
【问题描述】:
我想将日期和时间转换为用户请求的时区。日期和时间采用 GMT 格式。我尝试了解决方案,但最终字符串在结果日期中包含 GMT 字符串,例如 (2019-09-18T01:44:35GMT-04:00)。我不想在结果输出中出现 GMT 字符串。
public static String cnvtGMTtoUserReqTZ(String date, String format, String timeZone) {
// null check
if (date == null)
return null;
// create SimpleDateFormat object with input format
SimpleDateFormat sdf = new SimpleDateFormat(format);
// set timezone to SimpleDateFormat
sdf.setTimeZone(TimeZone.getTimeZone(timeZone));
try {
// converting date from String type to Date type
Date _date = sdf.parse(date);
// return Date in required format with timezone as String
return sdf.format(_date);
} catch (ParseException e) {
//log.info("Exception in cnvtGMTtoUserReqTime ::: " + e);
}
return null;
}
Actual Output : 2019-09-18T01:44:35GMT-04:00
Expected Output: 2019-09-18T01:44:35-04:00
【问题讨论】:
-
Dude.. 甚至 是 您使用的格式是什么?请在这里与我们合作..
-
另外,如果您使用
sdf解析并使用sdf格式化结果日期,那么什么都不会改变.. -
如果您只想删除
GMT字符串,为什么还要解析日期。你不能把它从字符串中删除吗? -
嗨@DanielBarbarian 我可以用''替换
GMT,但我想使用SimpleDateFormatter Calss -
您不应该使用
SimpleDateFormat、TimeZone和Date。这些类设计不佳且过时已久,尤其是第一个类是出了名的麻烦。而是使用DateTimeFormatter、ZoneId和来自java.time, the modern Java date and time API 的其他类。
标签: java datetime timezone gmt