簡體   English   中英

如何將字符串轉換為日期(HHMMMDD)(小時,月,日)

[英]how to convert string to date (HHMMMDD) (hour, month, day-of-month)

我嘗試將字符串轉換為日期類型。 這就是我所做的全部。

DateTimeFormatter formatter = DateTimeFormatter.ofPattern("HHMMMDD");

String date = "23Mar25";

System.out.println(date);

LocalDate localDate = LocalDate.parse(date, formatter);

System.out.println(localDate);

我得到了錯誤信息

Text '23Mar25' could not be parsed: 
Unable to obtain LocalDate from TemporalAccessor: 
{MonthOfYear=3, DayOfYear=25},ISO resolved to 23:00 of type 
java.time.format.Parsed at 
java.time.format.DateTimeFormatter.createError(DateTimeFormatter.java:1920)

有人可以幫我解決嗎?

tl; dr

LocalTime.parse( "23Mar25" , DateTimeFormatter.ofPattern ( "HHMMMdd", Locale.US )
         .toString()  // 23:00

…和…

MonthDay.parse( "23Mar25" , DateTimeFormatter.ofPattern ( "HHMMMdd", Locale.US )
        .toString()   // --03-25

細節

如果您確定輸入確實代表一個小時,一個月和一個月中的某天…

DateTimeFormatter

定義一個DateTimeFormatter 確保為人類語言指定Locale ,以翻譯月份的縮寫名稱。

String input = "23Mar25";
DateTimeFormatter f = DateTimeFormatter.ofPattern ( "HHMMMdd", Locale.US );

LocalTime

兩次使用該格式化程序。 一次產生一個一天中的時間作為LocalTime對象以保持一天中的小時。

LocalTime lt = LocalTime.parse ( input, f );

MonthDay

再次產生一個MonthDay對象來保存月份和月份。

MonthDay md = MonthDay.parse ( input , f  );

ZoneId

要使該時刻成為特定值,我們必須指定一個年份和一個時區。 如果要使用當前年份,則也需要一個時區。 請記住,在任何給定時刻,日期和時間在全球范圍內都會發生變化。

continent/region的格式指定正確的時區名稱 ,例如America/MontrealAfrica/CasablancaPacific/Auckland 切勿使用ESTIST等3-4個字母的縮寫,因為它們不是真實的時區,不是標准化的,甚至不是唯一的(!)。

ZoneId z = ZoneId.of ( "America/Montreal" ); 

LocalDate

通過為我們的MonthDay對象分配年份來確定LocalDate對象。

int yearNumber = Year.now ( z )
                     .getValue ( ) ;
LocalDate ld = md.atYear ( yearNumber );

ZonedDateTime

LocalTime結合使用以獲取准確的時刻,即時間軸上的一點。 結果是一個ZonedDateTime對象。

ZonedDateTime zdt = ZonedDateTime.of ( ld, lt, z );

轉儲到控制台。

System.out.println ( "input: " + input );
System.out.println ( "lt: " + lt );
System.out.println ( "md: " + md );
System.out.println ( "ld: " + ld );
System.out.println ( "zdt: " + zdt );

輸入:25年3月23日

lt:23:00

md:-03-25

ld:2017-03-25

zdt:2017-03-25T23:00-04:00 [美國/蒙特利爾]

OffsetDateTime

如果您的輸入用於UTC ,則可以使用ZoneOffset.UTC常量和OffsetDateTime類代替上面的代碼,而不是ZoneIdZonedDateTime

OffsetDateTime zdt = OffsetDateTime.of ( ld, lt, ZoneOffset.UTC );

ISO 8601

注意輸出,即toString方法生成的字符串。 解析/生成字符串時,java.time類默認使用ISO 8601標准格式。 我強烈建議您和您的數據源使用這些標准格式,而不要像在“問題”中看到的那樣發明自己的格式。 java.time類可以直接解析以及生成此類標准字符串,而無需指定格式化模式。

若要生成其他格式的字符串,請使用DateTimeFormatter類。 該主題在其他許多Stack Overflow頁面中都有介紹,因此請搜索許多示例和更多討論。

DateTimeFormatter formatter = DateTimeFormatter.ofPattern("HHMMMDD");

它使用以下模式:

HH: 2 spaces for hour
MMM: 3 spaces for month
DD: 2 spaces for day

我認為您需要這樣的格式:`ddmmmyy

dd: 2 spaces for day
mmm: 3 spaces for month
yy: 2 spaces for year

暫無
暫無

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

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