3

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

dreamcrash
  • 47,137
  • 25
  • 94
  • 117
Najme
  • 53
  • 6
  • You have an overflow here, i.e. those _milli_ seconds you added are interpreted as 364000 seconds or 4 days 5 hours 6 minutes and 40 seconds. Those are added to the parsed date. Try to add `df.setLenient(false)` and you should get an error. – Thomas Mar 26 '21 at 06:45
  • I recommend you don’t use `SimpleDateFormat` and `Date`. Those classes are poorly designed and long outdated, the former in particular notoriously troublesome. Instead use `LocalDateTime` and `DateTimeFormatter`, both from [java.time, the modern Java date and time API](https://docs.oracle.com/javase/tutorial/datetime/). – Ole V.V. Mar 26 '21 at 10:49

1 Answers1

2

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.

Arvind Kumar Avinash
  • 71,965
  • 6
  • 74
  • 110