简体   繁体   中英

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".
Required Date Format: "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. 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):

   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));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM