簡體   English   中英

將字符串yyyy-mm-dd hh:mm:ss + timezone格式化為DateTime

[英]Format String yyyy-mm-dd hh:mm:ss +timezone into DateTime

我需要格式化一個看起來像這樣的字符串:

"2018-07-20 18:53:46.598000 +02:00:00" 

變成這樣的DateTime對象:

20/07/2018 (HH with Timezone applied):53:46

我的方法是:

String dateTimePattern = "dd/MM/yyyy HH:mm:ss";
SimpleDateFormat dateTimeFormat = new SimpleDateFormat(dateTimePattern);                                                                                                                                                         
Date feUltModDateTime = dateTimeFormat.parse(feUltMod);
feUltMod = feUltModDateTime.toString();

但是我收到一個解析錯誤:

java.text.ParseException: Unparseable date: "2018-07-20 18:53:46.598000 +02:00:00"

java.time

    DateTimeFormatter origFormatter 
            = DateTimeFormatter.ofPattern("uuuu-MM-dd HH:mm:ss.SSSSSS XXXXX");
    DateTimeFormatter desiredFormatter = DateTimeFormatter.ofPattern("dd/MM/uuuu HH:mm:ss");
    ZoneId desiredZone = ZoneId.of("America/Fort_Nelson");

    String feUltMod = "2018-07-20 18:53:46.598000 +02:00:00";
    OffsetDateTime dateTime = OffsetDateTime.parse(feUltMod, origFormatter);
    ZonedDateTime dateTimeWithTimeZoneApplied = dateTime.atZoneSameInstant(desiredZone);
    feUltMod = dateTimeWithTimeZoneApplied.format(desiredFormatter);
    System.out.println(feUltMod);

該代碼段的輸出為:

20/07/2018 09:53:46

通常,您需要兩個格式化程序才能將日期或日期時間從一種格式轉換為另一種格式:一種指定要從中轉換的格式,另一種指定要從轉換的格式。

變成這樣的DateTime對象

日期時間對象沒有格式,因此在這方面不能“像這樣”。 上述代碼段中的dateTimeWithTimeZoneApplied在指定的時區中,因此調整了小時數。 轉換到該時區后,我已按照您提到的格式將其格式化為字符串,以防萬一您想要這樣做(我不清楚)。

我正在使用並推薦使用java.time(現代Java日期和時間API)。 您使用的日期和時間類DateSimpleDateFormat早已過時且設計不良,因此不值得與之抗爭。 而且SimpleDateFormat僅支持毫秒,因此只能在秒上精確地使用3個小數,而不是6個小數才能正確工作。

鏈接: Oracle教程:Date Time解釋了如何使用java.time

    final SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");
    Date df = new Date();
    String yourString = sdf.format(df);

    Date parsedDate = sdf.parse(yourString);
    Timestamp sqlDate = new java.sql.Timestamp(parsedDate.getTime());

上面的代碼將為您提供當前的時間戳,時間戳將提供更好的可行性

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM