Search code examples
javadateparsingsimpledateformat

parsing date using simpleDateFormat java


I want to parse an String to Date but the date obtained is incorrect. my code is like :

SimpleDateFormat df = new SimpleDateFormat("dd-MMM-yy hh.mm.ss.S a");
date1 = df.parse("17-DEC-19 05.40.39.364000000 PM");

but date1 is: Sat Dec 21 22:47:19 IRST 2019

I need to date: * Dec 17 17:40:39 IRST 2019


Solution

  • The SimpleDateFormat does not have precision beyond milliseconds (.SSS).

    import java.text.ParseException;
    import java.text.SimpleDateFormat;
    import java.util.Date;
    import java.util.Locale;
    
    public class Main {
        public static void main(String[] args) throws ParseException {
            SimpleDateFormat df = new SimpleDateFormat("dd-MMM-yy hh.mm.ss.SSS a", Locale.ENGLISH);
            Date date1 = df.parse("17-DEC-19 05.40.39.364 PM");
            System.out.println(date1);
        }
    }
    

    Output:

    Tue Dec 17 17:40:39 GMT 2019
    

    Note that the java.util date-time API and their formatting API, SimpleDateFormat are outdated and error-prone. It is recommended to stop using them completely and switch to the modern date-time API* .

    Using modern date-time API:

    import java.time.LocalDateTime;
    import java.time.format.DateTimeFormatter;
    import java.time.format.DateTimeFormatterBuilder;
    import java.util.Locale;
    
    public class Main {
        public static void main(String[] args)  {
            DateTimeFormatter df = new DateTimeFormatterBuilder()
                    .parseCaseInsensitive() // For case-insensitive (e.g. AM/am) parsing
                    .appendPattern("dd-MMM-yy hh.mm.ss.n a")
                    .toFormatter(Locale.ENGLISH);
            
            LocalDateTime ldt = LocalDateTime.parse("17-DEC-19 05.40.39.364000000 PM", df);
            System.out.println(ldt);
        }
    }
    

    Output:

    2019-12-17T17:40:39.364
    

    Learn more about the modern date-time API from Trail: Date Time.


    * For any reason, if you have to stick to Java 6 or Java 7, you can use ThreeTen-Backport which backports most of the java.time functionality to Java 6 & 7. If you are working for an Android project and your Android API level is still not compliant with Java-8, check Java 8+ APIs available through desugaring and How to use ThreeTenABP in Android Project.