Java Date Exception - java

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)

Related

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

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)

I got java.text.ParseException: Unparseable date: "" with extending zero at last eg:- 2014-11-26 12:22:44.0

Please help me with the following code. I got unparseable date exception.
public static Date getUtilDateFromString(String date) throws ParseException {
return getUtilDateFromString(date, null);
}
public static Date getUtilDateFromString(String date, String format)
throws ParseException {
if (format == null || "".equals(format)) {
format = "yyyy/MM/dd HH:mm:ss";
}
DateFormat dateFormat = new SimpleDateFormat(format);
return dateFormat.parse(date);
}
The Date format should be yyyy-MM-dd HH:mm:ss.S since you're dealing with milliseconds. Your date pattern has mistakes too.
This works:
System.out.println(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.S").parse("2014-11-26 12:22:44.0"));
Output:
Wed Nov 26 12:22:44 CAT 2014
I would check the String date variable you are using, it seems that it does not fit the format you are trying to implement.
For example if you call getUtilDateFromString("2014-12-06 12:26:11") it will not work because the SimpleDateFormat will be expecting a String date with the format "yyyy/MM/dd HH:mm:ss".
If you call getUtilDateFromString("2014/12/06 12:26:11") will work perfectly fine because the
String date fits the format "yyyy/MM/dd HH:mm:ss".
Hope it helps.

How to save current date and time to database using java?

I am using the following code to get the current date and time, but the output is not what I am expecting and I cant save it into database.
Output >> current: Tue Mar 05 09:58:26 EST 2013
Expected output >> current: 2013-03-05 9:58:26
.....{
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
SimpleDateFormat parseFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date date = new Date();
try {
System.out.println("current: " +parseFormat.parse(dateFormat.format(date)));
return parseFormat.parse(dateFormat.format(date));
} catch (ParseException ex) {
Logger.getLogger(ConstructionModel.class.getName()).log(Level.SEVERE, null, ex);
}
return date;
}
......
ps.setDate(....) <<< failed
Database
name type
mydate Date
You don't need to parse before formatting:
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date date = new Date();
String frmtdDate = dateFormat.format(date);
System.out.println("frmtdDate: " + frmtdDate);
However, if you are trying to fit the date into some DB statement, you should not do it in the form of text, instead use one of the JDBC setters that utilize java.sql.Date or java.sql.Timestamp
You need to use sql timestamp for saving to the database. Convert your java.util.Date to java.sql.Timestamp:
ps.setTimestamp(new java.sql.Timestamp(myDate.getTime()));
format takes a Date and returns a formatted String. parse takes a formatted String and returns a Date object. When you do parseFormat.parse(dateFormat.format(date)) you are converting Date to String and to Date again. The value that is printed is the default representation provided by Date.toString() instead of the formatted string.
System.out.println("current: " +dateFormat.format(date));

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.

Categories

Resources