I am facing some problem to parse the date format dd-m-y
with SimpleDateFormat
class in Java.
So is there any date formatter for this date format type (12-oct-14
)?
I am facing some problem to parse the date format dd-m-y
with SimpleDateFormat
class in Java.
So is there any date formatter for this date format type (12-oct-14
)?
SimpleDateFormat sdf = new SimpleDateFormat("dd-MMM-yy")
If you are using Java 8 or 9, then please refer this
The other answers might have worked, but there's a little detail that most people often forget.
The month name in your input ("oct") is in English (or in some other language where October's abbreviation is "oct", but I'm assuming English here, as this doesn't change the answer).
When you create a SimpleDateFormat
, it uses the JVM default locale (represented by the class java.util.Locale
). In your case, new SimpleDateFormat("dd-MMM-yy")
worked because your JVM's default locale probably is already English.
But the default locale can be changed, even at runtime, and even by other applications running in the same JVM. In other words, you have no control over it and no guarantees at all that the default will always be English.
In this case, if you know that the input is always in English, it's safer and much better to explicity use a java.util.Locale
in the formatter:
SimpleDateFormat sdf = new SimpleDateFormat("dd-MMM-yy", Locale.ENGLISH);
Even better is to use - if available to you - the Java 8's date/time API. This API is much better than SimpleDateFormat
, because it solves many of the problems this class has.
The code might look harder in the beginning, but it's totally worth to learn the new API:
DateTimeFormatter fmt = new DateTimeFormatterBuilder()
// case insensitive, for month name
.parseCaseInsensitive()
// pattern for day-month-year
.appendPattern("dd-MMM-yy")
// use English for month name
.toFormatter(Locale.ENGLISH);
System.out.println(LocalDate.parse("12-oct-14", fmt));
String format = "dd-MMM-yy";
SimpleDateFormat sdf = new SimpleDateFormat(format);
System.out.println(sdf.format(new Date()));
System.out.println(sdf.parse("12-oct-14"));
Result:
22-Mar-18
Sun Oct 12 00:00:00 UTC 2014
First step: create a DateTimeFormatter
by using the format you need and the ofPattern()
method.
Second step: create two LocalDate
objects with the .parse(CharSequence text, DateTimeFormatter format)
method.
Third step: use firstDate.untill(secondDate)
and receive a Period
object.
Fourth step: use .getDays()
method to get the number of days from the Period
object.