如何将字符串 (HH:mm) 设置为当前日期的 UTC 时间并将其转换为本地时间

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


一只甜甜圈
浏览 56回答 3
3回答

慕慕森

强烈建议您使用现代 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:002019-11-04T06:00:00Z[UTC]您可以根据需要使用不同的DateTimeFormatters 进行格式化。

肥皂起泡泡

尝试如下所示。public String getDateTimeInUTC(String yourTime){     Calendar cal = Calendar.getInstance();    SimpleDateFormat currentDate= new SimpleDateFormat("MMM dd, yyyy ");    String currentDateTime = currentDate.format(cal.getTime())+yourTime; // here concate your time with current date.    System.out.println("Current date with given time: "+currentDateTime);    SimpleDateFormat df = new SimpleDateFormat("MMM dd, yyyy HH:mm", Locale.ENGLISH);    df.setTimeZone(TimeZone.getTimeZone("UTC"));    Date date = null;    try {       date = df.parse(currentDateTime);    } catch (ParseException e) {       e.printStackTrace();    }    df.setTimeZone(TimeZone.getDefault());    String formattedDate = df.format(date);    return formattedDate;}getDateTimeInUTC像下面这样调用String strTime = "12:10"; // your string time in HH:mm formatString finalDateTime = getDateTimeInUTC(strTime);System.out.println("Final date-time in UTC: "+finalDateTime);输出:Current date with  given time: Nov 04, 2019 12:10Final date-time in UTC: Nov 04, 2019 18:10

素胚勾勒不出你

您可以查看一下:Calendar calendar = Calendar.getInstance();calendar.setTime(new Date());//change the format according to your needSimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");//Here you say to java the initial timezone. This is the secretsdf.setTimeZone(TimeZone.getTimeZone("UTC"));//Will print in UTCSystem.out.println(sdf.format(calendar.getTime()));    //Here you set to your timezonesdf.setTimeZone(TimeZone.getDefault());//Will print on your default TimezoneSystem.out.println(sdf.format(calendar.getTime()));
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java