java - 如何设置字符串(HH :mm) to UTC time with current date and convert it to local time

标签 java android date calendar datetime-format

我需要将 (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

这样做,很容易

  1. 解析您收到的时间
  2. 获取当前日期并
  3. 将它们组合成具有特定时区的日期时间表示形式

看这个小例子:

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/

相关文章:

JAVA - 在 Linux 上接收 UDP 数据包时出现问题

android - GoogleApiClient : "Result has already been consumed" in multi-thread Android app

java - 不存在类型变量 R 的实例,因此 Observable 符合 Observable?

date - Kettle数据整合: dates always blank on excel output or excel writer

java - Weblogic10.3.5 eclipse服务器配置问题

java - 无法获得正确的输出 xml 文件

android - 如何设置透明边框按钮

java仅使用逻辑,没有日历,日期或类似的两个日期之间的差异

php - 如果不是当前日期,则将 SQL 日期变为红色

java - 查找给定 Realm 模式的 Java 类