簡體   English   中英

無法以我需要的格式將日期字符串轉換為日期 object

[英]Unable to convert date string to date object in my required format

我想將字符串轉換為日期。 我嘗試了不同的場景,但無法將其轉換為我需要的格式。

字符串格式:“dd/MM/yyyy hh:mm aa”。
所需日期格式:“yyyy-MM-dd HH:mm:ss.SSS”。

SimpleDateFormat originalFormat = new SimpleDateFormat("dd/MM/yyyy hh:mm aa");
Date date = originalFormat.parse("03/02/2007 05:36 PM");
      
SimpleDateFormat targetFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
String originalDate = targetFormat.format(date);
        
Date dateValue = targetFormat.parse(originalDate);
        
String finalDate = targetFormat.format(dateValue);
Date requiredDate = targetFormat.parse(finalDate);

我以我需要的格式將結果作為字符串。 但我需要它作為日期。 轉換后,我得到“EEE MMM dd HH:mm:ss zzzz yyyy”這種格式。 該怎么辦?

提前致謝。

我不明白 - “我以我需要的格式將結果作為字符串。但我需要它作為日期”。 如果您想要特定格式的日期,則可能只是使用格式將日期轉換為字符串。 我使用 java.time.LocalDateTime 和 java.time.format.DateTimeFormatter (可從 Java 8 獲得):

   String strDate = "03/02/2007 05:36 PM";
   DateTimeFormatter format = DateTimeFormatter.ofPattern("dd/MM/yyyy hh:mm a");
   LocalDateTime dt = LocalDateTime.parse(strDate, format);
   
   DateTimeFormatter newFormat = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.SSS");
   System.out.println(dt.format(newFormat));

暫無
暫無

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

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