Incorrect date parsing using SimpleDateFormat, Java

穿精又带淫゛_ 提交于 2019-12-12 10:38:14

问题


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?


回答1:


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



来源:https://stackoverflow.com/questions/10606126/incorrect-date-parsing-using-simpledateformat-java

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!