简体   繁体   English

无法以我需要的格式将日期字符串转换为日期 object

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

I want to convert string to date.我想将字符串转换为日期。 I tried different scenarios but unable to convert it to my required format.我尝试了不同的场景,但无法将其转换为我需要的格式。

String Format: "dd/MM/yyyy hh:mm aa".字符串格式:“dd/MM/yyyy hh:mm aa”。
Required Date Format: "yyyy-MM-dd HH:mm:ss.SSS".所需日期格式:“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);

I am getting result as string in my required format.我以我需要的格式将结果作为字符串。 But I need it as date.但我需要它作为日期。 After conversion I am getting in "EEE MMM dd HH:mm:ss zzzz yyyy" this format.转换后,我得到“EEE MMM dd HH:mm:ss zzzz yyyy”这种格式。 What to do?该怎么办?

Thanks in Advance.提前致谢。

I do not understand - "I am getting result as string in my required format. But I need it as date".我不明白 - “我以我需要的格式将结果作为字符串。但我需要它作为日期”。 If you want date in certan format it may be only date converted to string using format.如果您想要特定格式的日期,则可能只是使用格式将日期转换为字符串。 I use java.time.LocalDateTime and java.time.format.DateTimeFormatter (avalible from Java 8):我使用 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