SimpleDateFormat.parse() - generates wrong date for different date-formats - java

Below is my code to parse the date using SimpleDateFormat with pattern:
String pattern = "yyyy-MM-dd";
SimpleDateFormat format = new SimpleDateFormat(pattern);
try {
Date date = format.parse("05-21-2030");
System.out.println(date);
} catch (ParseException e) {
e.printStackTrace();
}
You can see the date which I passed to parse is different from date format which is specified in SimpleDateFormat. In this case I was expecting kind of excpetion as format is different but it parsed successfully with some different date values. I got the output - Tue Mar 22 00:00:00 IST 12
When I pass the same format like 2030-05-21 it works fine.
Can you guys please let me know how can I prevent such things in my code?

Basically you want SimpleDateFormat to be strict, so set lenient to false.
SimpleDateFormat format = new SimpleDateFormat(pattern);
format.setLenient(false);

If you can afford using Java 8 time API, its formatter works as expected:
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
try {
LocalDate date = LocalDate.parse("2030-05-21", formatter);
System.out.println(date);
LocalDate date2 = LocalDate.parse("05-21-2030", formatter);
System.out.println(date2);
} catch (DateTimeParseException e) {
e.printStackTrace();
}
Output:
2030-05-21
java.time.format.DateTimeParseException: Text '05-21-2030' could not be parsed at index 0
at java.time.format.DateTimeFormatter.parseResolved0(DateTimeFormatter.java:1947)
at java.time.format.DateTimeFormatter.parse(DateTimeFormatter.java:1849)
at java.time.LocalDate.parse(LocalDate.java:400)
at java8.Snippet.main(Snippet.java:25)

Related

Java Date Exception

want to convert String date into java.util.Date object getting the following exception.
java.text.ParseException: Unparseable date: "04/18/2018 12:00 AM"
input : "04/18/2018 12:00 AM"
private Date convertToDate(String date) {
try {
DateFormat formatter = new SimpleDateFormat("dd-MMM-yyyy,HH:mm:ss aaa");
return formatter.parse(date);
} catch (ParseException e) {
e.printStackTrace();
}
return null;
}
What I want the date in this format
2018-04-09 09:22:57 AM
For the date format that you specified dd-MMM-yyyy,HH:mm:ss aaa, the date string should be in the following format: 18-Apr-2018,03:22:15 AM. You are not using the correct delimiters in your example.
Tip: this is a nice web resource to test date formats.
That input is not correct format because you try to parse other format... Try to input your date in this way:
18-Apr-2018,03:26:38 AM
For the input you do, the format is: MM/dd/yyyy HH:mm a (04/18/2018 12:00 AM)

Java Date Parsing from string

I'm trying to parse a String into Data, I create the DataParser, in according to date format, the code I wrote is this:
String date_s = "04-May-2017 17:28:27";
DateFormat formatter = new SimpleDateFormat("dd-MMM-yyyy HH:mm:ss");
Date date;
try {
date = formatter.parse(date_s);
System.out.println(date);
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
When I execute this, I got always an exception
java.text.ParseException: Unparseable date: "04-May-2017 17:28:27"
I don't understand why the data is not parsed, someone can help me?
This thread of answers would not be complete without the modern solution. These days you should no longer use Date and SimpleDateFormat, but switch over to the newer date and time classes:
DateTimeFormatter formatter
= DateTimeFormatter.ofPattern("dd-MMM-yyyy HH:mm:ss", Locale.ENGLISH);
LocalDateTime dateTime;
try {
dateTime = LocalDateTime.parse(date_s, formatter);
System.out.println(dateTime);
} catch (DateTimeParseException e) {
System.err.println(e);
}
This prints
2017-05-04T17:28:27
(LocalDateTime.toString() returns ISO 8601 format) If leaving out Locale.ENGLISH, on my computer I get
Text '04-May-2017 17:28:27' could not be parsed at index 3
Index 3 is where it say May, so the message is somewhat helpful.
LocalDateTime and DateTimeFormatter were introduced in Java 8, but have also been backported to Java 6 and 7.
the string you want to parse is local dependent (the word May is English), so the jvm is not able to infer that may is the month of may in English
define the formatter using the constructor qith the locale.
DateFormat formatter = new SimpleDateFormat("dd-MMM-yyyy HH:mm:ss",Locale.ENGLISH);
You need another constructor with a Locale that supports MMM (May)
DateFormat formatter = new SimpleDateFormat("dd-MMM-yyyy HH:mm:ss",Locale.US)
or using standard format dd-MM-yyyy with month digits.
(Sorry, in the meantime the answer was already posted)

String to Date with month all lowercase in java

I have a string that contains a date, in the following format:
dd-mm-yyyy
with the month that is all lowercased. For example:
25-aug-2019
Now i tried to use SimpleDateFormat to convert my string to a Date, but i have the following exception:
java.text.ParseException: Unparseable date: "25-aug-2019"
at java.text.DateFormat.parse(Unknown Source)
at org.whoislibrary.servers.WhoisCom.parseResponse(WhoisCom.java:37)
at org.whoislibrary.WhoisAbstract.executeQuery(WhoisAbstract.java:44)
at org.whoislibrary.WhoisCommand.executeQuery(WhoisCommand.java:69)
at org.whoislibrary.WhoisMain.main(WhoisMain.java:10)
This is the code that i used:
DateFormat df = new SimpleDateFormat("dd-MM-yyyy");
try {
Date expDate = df.parse(dateString).trim());
System.out.println(expDate.toString());
} catch (ParseException e) {
e.printStackTrace();
}
I think the problem is that MM refers to month name that start with a capital letter (Aug, Jul etc). There is an option, or a class like SimpleDateFormat that help me to convert that string into a Date. or it must be done Manually?
Well in your code you have:
new SimpleDateFormat("dd-MM-yyyy")
Which should be:
new SimpleDateFormat("dd-MMM-yyyy")
Since the month part in your string has 3 letters (MMM) and not 2 (MM)
use dd-MMM-yyyy
Your date "25-aug-2019" is in "dd-MMM-yyyy" format not "dd-MM-yyyy". So you get parse error. You should use "dd-MMM-yyyy" while creating SimpleDateFormat object.
DateFormat df = new SimpleDateFormat("dd-MMM-yyyy");
try {
Date expDate = df.parse("25-aug-2019");
System.out.println(expDate.toString());
} catch (ParseException e) {
e.printStackTrace();
}
Refer javaDocs java.text.SimpleDateFormat

Parsing date from Calendar in Java

I am having following function
public static Date parseDate(String date, String format) throws ParseException
{
SimpleDateFormat formatter = new SimpleDateFormat(format);
return formatter.parse(date);
}
I am using this as follows in my code
Calendar eDate = Calendar.getInstance();
eDate.add(Calendar.DAY_OF_MONTH,10);
Date date = null;
try {
date = parseDate(eDate.getTime().toString(),"yyyy-MM-dd hh-mm-ss");
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
But it is throwing -
java.text.ParseException: Unparseable date
What is the problem here?
The format is not stored in the Date. It is stored in the String. The Date#toString() returns a fixed format which is described in its Javadoc.
Do the formatting only at the moment you need to display a Date to a human as a String.
Calendar calendar = Calendar.getInstance();
calendar.add(Calendar.DAY_OF_MONTH, 10);
Date date = calendar.getTime();
String formattedDate = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(date);
System.out.println(formattedDate);
Note that MM stands for months and mm for minutes. See also SimpleDateFormat javadoc.
You'll be happy to hear that there's never a need to parse a date from a Calendar object: The way to pull a Date out of a Calendar is via the getTime() method.
EDIT:
To output the date in eDate in ISO style format:
final DateFormat isoFormat = new SimpleDateFormat("yyyy-MM-dd HH-mm-ss");
String formattedDate = isoFormat.format(eDate.getTime());
That's untested, but I think it should work.
You're currently formatting with the default format from java.util.Date, and then parsing with a potentially different format. You should also change your format string - it's currently using a 12 hour clock with no am/pm indicator, and minutes twice. I think you mean: "yyyy-MM-dd HH-mm-ss"
Don't use toString() for anything like that. toString() should be used only for debug messages.
Use DateFormat.format(..) to produce a string in a predictable form.
You're inserting a Zulu Timestamp (UNIX), getTime() returns the number of milliseconds since January 1, 1970, 00:00:00 GMT. Then you define the format as yyyy-mm-dd hh-mm-ss and try to parse the timestamp with this pattern. Which doesn't match.
You could use Date date = calendar.getTime(); and then format it via new SimpleDateFormat("yyyy-MM-dd HH-mm-ss").format(date);
you can simply use the date returned by the calendar, instead of transforming it into string and back into a date (apparently using a wrong date format). The date can be obtained by:
eDate.getTime()
There seems to be no need for SimpleDateFormat in your case.
Check the Date.toString() method.
The api states that it returns it in
the format:
dow mon dd hh:mm:ss zzz yyyy
which is:
Mon Jan 28 14:22:07 EST 2004
You are telling the parser to expect: 2004-01-28 14-22-07
eDate.getTime().toString()
returns a String representation of a date in this format:
dow mon dd hh:mm:ss zzz yyyy (see the java.util.Date API).
You are trying to parse a date using this format:
yyyy-mm-dd hh-mm-ss .
The code is correctly throwing the ParseException.

DateTime formatter

I am developing an application and I am stuck in converting string like 01/01/2037 01:00:00 AM
to Date
I used
SimpleDateFormat dateFormat = new SimpleDateFormat("dd-MM-yyyy hh.mm.ss.S aa")
Date d = dateFormat.parse(dateString);
but I get an error, any help will be appreciated.
you are converting this 01/01/2037 01:00:00 AM
therefore use
SimpleDateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy hh:mm:ss aa")
(more info in [documentation])1
then
Date date = dateFormat.parse("01/01/2037 01:00:00 AM");
keep in mind you have to wrap a try-catch around the parse method.
The problem is that the format you declared is nothing like the String you are trying to parse:
your String uses / to separate day, month, year while in your formatter you use -
your string separates hours with a dot, while in the formatter you use :
you do not have milliseconds in your string while you declared them in the formatter.
The following code should work:
SimpleDateFormat dateFormat = new SimpleDateFormat("dd-MM-yyyy hh.mm.ss.S aa");
try {
Date date = dateFormat.parse("01-01-2037 01.00.00.000 AM");
System.out.println(date);
} catch (ParseException e) {
e.printStackTrace();
}

Categories

Resources