我从一个字符串中解析了一个java.util.Date,但它将本地时区设置为date对象的时区。
在解析Date的字符串中没有指定时区。我想设置date对象的特定时区。
我该怎么做呢?
我从一个字符串中解析了一个java.util.Date,但它将本地时区设置为date对象的时区。
在解析Date的字符串中没有指定时区。我想设置date对象的特定时区。
我该怎么做呢?
当前回答
calendar是使用JDK类处理时区的常用方法。Apache Commons还有一些可能有用的替代方案/实用程序。Edit Spong的留言提醒我,我听说Joda-Time真的很不错(尽管我自己没有用过)。
其他回答
这段代码在我正在开发的应用程序中很有帮助:
Instant date = null;
Date sdf = null;
String formatTemplate = "EEE MMM dd yyyy HH:mm:ss";
try {
SimpleDateFormat isoFormat = new SimpleDateFormat("EEE MMM dd yyyy HH:mm:ss");
isoFormat.setTimeZone(TimeZone.getTimeZone(ZoneId.of("US/Pacific")));
sdf = isoFormat.parse(timeAtWhichToMakeAvailable);
date = sdf.toInstant();
} catch (Exception e) {
System.out.println("did not parse: " + timeAtWhichToMakeAvailable);
}
LOGGER.info("timeAtWhichToMakeAvailable: " + timeAtWhichToMakeAvailable);
LOGGER.info("sdf: " + sdf);
LOGGER.info("parsed to: " + date);
在这里,您可以获得日期如“2020-03-11T20:16:17”并返回“11/Mar/2020 - 20:16”
private String transformLocalDateTimeBrazillianUTC(String dateJson) throws ParseException {
String localDateTimeFormat = "yyyy-MM-dd'T'HH:mm:ss";
SimpleDateFormat formatInput = new SimpleDateFormat(localDateTimeFormat);
//Here is will set the time zone
formatInput.setTimeZone(TimeZone.getTimeZone("UTC-03"));
String brazilianFormat = "dd/MMM/yyyy - HH:mm";
SimpleDateFormat formatOutput = new SimpleDateFormat(brazilianFormat);
Date date = formatInput.parse(dateJson);
return formatOutput.format(date);
}
calendar是使用JDK类处理时区的常用方法。Apache Commons还有一些可能有用的替代方案/实用程序。Edit Spong的留言提醒我,我听说Joda-Time真的很不错(尽管我自己没有用过)。
将日期转换为字符串,并使用SimpleDateFormat。
SimpleDateFormat readFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
readFormat.setTimeZone(TimeZone.getTimeZone("GMT" + timezoneOffset));
String dateStr = readFormat.format(date);
SimpleDateFormat writeFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
Date date = writeFormat.parse(dateStr);
DateFormat使用。例如,
SimpleDateFormat isoFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
isoFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
Date date = isoFormat.parse("2010-05-23T09:01:02");