我需要将 (HH:mm) 格式的字符串转换为本地时区,该字符串应该是 UTC 时间。如何将当前日期添加到字符串并将其转换为本地时间。
我尝试过使用日历
String utcTimeString = "06:00";
SimpleDateFormat sdf = new SimpleDateFormat("HH:mm", Locale.getDefault());
sdf.setTimeZone(TimeZone.getTimeZone("UTC"));
Calendar now = Calendar.getInstance(Locale.getDefault());
now.setTime(sdf.parse(utcTimeString));
最佳答案
强烈建议您使用现代 API 来获取日期、时间、时区、偏移量、日历等:
java.time
这样做,很容易
- 解析您收到的时间
- 获取当前日期并
- 将它们组合成具有特定时区的日期时间表示形式
看这个小例子:
public static void main(String[] args) {
// create a time object from the String
LocalTime localTime = LocalTime.parse("06:00", DateTimeFormatter.ofPattern("HH:mm"));
// print it once in an ISO format
System.out.println(localTime.format(DateTimeFormatter.ISO_TIME));
// receive the date of today
LocalDate today = LocalDate.now();
// then use the date and the time object to create a zone-aware datetime object
ZonedDateTime zdt = LocalDateTime.of(today, localTime).atZone(ZoneId.of("UTC"));
// print it
System.out.println(zdt.format(DateTimeFormatter.ISO_ZONED_DATE_TIME));
}
输出为
06:00:00
2019-11-04T06:00:00Z[UTC]
您可以使用不同的 DateTimeFormatter
根据需要进行格式化。
关于java - 如何设置字符串(HH :mm) to UTC time with current date and convert it to local time,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58690768/