Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Incorrect date parsing using SimpleDateFormat, Java

I need to parse a date from input string using date pattern "yyyy-MM-dd", and if date will come in any other format, throw an error.

This is my piece of code where I parse the date:

private void validateDate() throws MyException {
  Date parsedDate;
  String DATE_FORMAT = "yyyy-MM-dd";
  try{
    parsedDate = new SimpleDateFormat(DATE_FORMAT).parse(getMyDate());
    System.out.println(parsedDate);
  } catch (ParseException e) {
    throw new MyException(“Error occurred while processing date:” + getMyDate());
  }

}

When I have string like "2011-06-12" as input in myDate I will get output "Thu Sep 29 00:00:00 EEST 2011", which is good.

When I sent an incorrect string like “2011-0612”, I’m getting error as expected.

Problems start when I’m trying to pass a string which still has two “hyphens”, but number of digits is wrong. Example:

input string “2011-06-1211” result "Tue Sep 23 00:00:00 EEST 2014".

input string “2011-1106-12” result "Mon Feb 12 00:00:00 EET 2103".

I can't change input format of string date.

How I can avoid it?

like image 607
AndrewVP Avatar asked May 15 '12 17:05

AndrewVP


People also ask

What can I use instead of SimpleDateFormat?

DateTimeFormatter is a replacement for the old SimpleDateFormat that is thread-safe and provides additional functionality.

Is SimpleDateFormat deprecated?

Deprecated. A class for parsing and formatting dates with a given pattern, compatible with the Java 6 API.

Why is SimpleDateFormat not thread-safe?

2.2.Date formats are not synchronized. It is recommended to create separate format instances for each thread. If multiple threads access a format concurrently, it must be synchronized externally. So SimpleDateFormat instances are not thread-safe, and we should use them carefully in concurrent environments.

What does SimpleDateFormat parse do?

The parse() Method of SimpleDateFormat class is used to parse the text from a string to produce the Date. The method parses the text starting at the index given by a start position.


1 Answers

Have you tried calling setLenient(false) on your SimpleDateFormat?

import java.util.*;
import java.text.*;

public class Test {

    public static void main(String[] args) throws Exception {
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        format.setLenient(false);
        Date date = format.parse("2011-06-1211"); // Throws...
        System.out.println(date);
    }
}

Note that I'd also suggest setting the time zone and locale of your SimpleDateFormat. (Alternatively, use Joda Time instead...)

like image 52
Jon Skeet Avatar answered Sep 28 '22 00:09

Jon Skeet