Java SimpleDateFormat Cannot format given Object as a Date - java

I am trying to convert string to date using date format and used the following code but its shows an error.
public static Date ConvertStringtodate(String Date) throws ParseException {
DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
Date Teststart = dateFormat.parse(Date);
return Teststart;
}
public static void main(String[]agrs) throws ParseException {
System.out.println(ConvertStringtodate("2022.02.10 17:54:55"));
}
Here is the error
Exception in thread "main" java.lang.IllegalArgumentException: Cannot
format given Object as a Date at
java.text.DateFormat.format(DateFormat.java:310) at
java.text.Format.format(Format.java:157)

At the main method, you are sending date as "2022.02.10 17:54:55". However, you wrote format of the pattern as "yyyy-MM-dd hh:mm:ss". Change the pattern at the SimpleDateFormat constructor as "yyyy.MM.dd HH:mm:ss".

The problem for me was the slashes '/' in the date input. for some reason the. The input string was "01/01/1991" instead of "01-01-1991". So I just replaced the slashes with dashes and everything worked just fine.
private Date convertStringToDate(String payload) throws ParseException {
payload = payload.replace("/", "-");
SimpleDateFormat formatter = new SimpleDateFormat("dd-MM-yyyy", Locale.ENGLISH);
java.util.Date utilDate = formatter.parse(payload);
return new Date(utilDate.getTime());
}

Related

Making Java DateFormat work for Shorter Values

I have a program which reads a Dateformat from user once and for all at the beginning of program such as yyyy/MM/dd HH:mm:ss a
Later on the program parses a File and use the Dateformat for all dates in the file. But recently I got a file, where 99% of the dates were 2014/09/01 12:00:04 AM So The user can input yyyy/MM/dd HH:mm:ss a.
However one date in that file is simply 2014/09/01 where the date format yyyy/MM/dd HH:mm:ss a fails.
Why can't yyyy/MM/dd HH:mm:ss a format shorter dates such as in the format yyyy/MM/dd.
What I want is that the java program use the format yyyy/MM/dd HH:mm:ss a to parse the following two dates below:
2014/09/01 12:00:04 AM
2014/09/01
Thanks
You have to use two formats. Check the example below
DateFormat df = new DateFormat() {
static final String FORMAT1 = "yyyy/MM/dd HH:mm:ss";
static final String FORMAT2 = "yyyy/MM/dd";
final SimpleDateFormat sdf1 = new SimpleDateFormat(FORMAT1);
final SimpleDateFormat sdf2 = new SimpleDateFormat(FORMAT2);
#Override
public StringBuffer format(Date date, StringBuffer toAppendTo, FieldPosition fieldPosition) {
return null;
}
#Override
public Date parse(String source, ParsePosition pos) {
if (source.length() - pos.getIndex() == FORMAT1.length())
return sdf1.parse(source, pos);
return sdf2.parse(source, pos);
}
};
System.out.println(df.parse("2014/09/01 12:00:04 AM"));
System.out.println(df.parse("2014/09/01"));

Java SimpleDateFormat.parse throws : Unparseable date: "2015-10-06T08:00:00+00:00" (at offset 10)

Hello i have the following string with datetime:
public static String nextOccurenceString = "2015-10-06T08:00:00+00:00";
And i want to parse and format string into the following format by following pattern:
public static String pattern = "yyyy-MM-dd HH:mm:ss";
But when i try to call method which should parse the date string into date object i always get exception:
Unparseable date: "2015-10-06T08:00:00+00:00" (at offset 10)
Method is following:
public static void convertStringToDate(String dateString) {
try {
SimpleDateFormat sdf;
sdf = new SimpleDateFormat(pattern, Locale.ENGLISH);
Date test = sdf.parse(nextOccurenceString);
Logger.d(test.toString());
} catch (Exception e) {
Logger.e(e.getMessage());
}
}
And I'm using the standard formatting and parsing class:
http://developer.android.com/reference/java/text/SimpleDateFormat.html
How can i solve it please? Should replace something in nextOccurenceString or can i work with string in format like:
"2015-10-06T08:00:00+00:00" ?
Many thanks for any advice.
Your pattern is wrong. It must be:
public static String pattern = "yyyy-MM-dd'T'HH:mm:ssZ";
For more information read the javadoc of SimpleDateFormat
The correct pattern for your string is yyyy-MM-dd'T'HH:mm:ssZ (ISO 8601) and not yyyy-MM-dd HH:mm:ss

Converting string to java.util.date

I am trying to convert string in java.util.date but I am having following errors:
HelloWorld.java:10: error: incompatible types: Date cannot be converted to String
return FORMATTER.parse(date);
^
HelloWorld.java:16: error: incompatible types: String cannot be converted to Date
Date date = convertStringToDate("2015-08-03 09:19:00.000");
My code is below:
import java.text.SimpleDateFormat;
import java.util.Date;
public class HelloWorld{
private static final SimpleDateFormat FORMATTER = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
public static String convertStringToDate(String date) {
if(date!=null){
return FORMATTER.parse(date);
}
return null;
}
public static void main(String []args){
Date date = convertStringToDate("2015-08-03 09:19:00.000");
System.out.println(date);
}
}
Change your method signature into this instead:
public static Date convertStringToDate(String date)
SimpleDateFormat.parse returns a Date, not a String.
Also, you need to handle the checked ParseException that the parse method may throw, either by declaring throws ParseException in the signature (and handling the exception in main), or by wrapping the exception into a RuntimeException (effectively terminating the program when bad input is given):
public static Date convertStringToDate(String date) {
if (date != null) {
try {
return FORMATTER.parse(date);
} catch (ParseException e) {
// nothing we can do if the input is invalid
throw new RuntimeException(e);
}
}
return null;
}
Finally, you should notice that you can only parse hour values ranging from 1 to 12 with your current format (yyyy-MM-dd hh:mm:ss). If you'd want to parse according to the 24-hour clock, you should use the HH pattern for the hour part instead:
private static final DateFormat FORMATTER = new SimpleDateFormat(
"yyyy-MM-dd HH:mm:ss");
Your specified format is not matching with data format.
format "yyyy-MM-dd hh:mm:ss" is NOT compatible with data "2015-08-03 09:19:00.000" because of two reason: (1) AM/PM is missing in date as 'hh' takes 1-12 hrs , and (2) milliseconds present in date string
Replace below mentioned line and your issue will be resolved.
private static final SimpleDateFormat FORMATTER = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
But, none of the above mentioned issue can cause the exception you got as milliseconds is ignored by default.
Possible reasons of exception are return type of method "convertStringToDate" or hh having value beyond the range between01 and 12.
change return type from String to Date
Change date format hh to HH.
It is because you are trying to return a String from your method. Change it to Date.
public static Date convertStringToDate(String date) {
if(date!=null){
return FORMATTER.parse(date);
}
return null;
}

how to format date using SimpleDateFormat

I cannot format a date.
dateFormat.format() accepts a Date as argument. So I created a new Date()
It says the below Date() method is deprecated, and I get the below exception while running.
exception:
Exception in thread "main" java.lang.IllegalArgumentException at
java.util.Date.parse(Date.java:598)
public class MyDate {
public static void main(String[] args) {
Date date = new Date("2012-02-16T00:00:00.000-0500");
SimpleDateFormat dateFormat = new SimpleDateFormat(
"dd-MMM-yyyy HH:mm:ss");
String stringDate = dateFormat.format(date);
System.out.println(stringDate); // how do I test this conversion??
}
}
My database has date of the format - 2012-02-16T00:00:00.000-0500
I need to convert it to string of the format : dd-MMM-yyyy HH:mm:ss
I'm using Java6
Thanks to #Andy Brown. In addition to what Andy Brown has answered, I'm posting the complete snippet
Complete Solution:
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
public class SampleDate {
public static void main(String[] args) throws ParseException {
DateFormat parseFormat = new SimpleDateFormat(
"yyyy-MM-dd'T'HH:mm:ss.SSSZ");
Date date = parseFormat.parse("2012-03-16T00:00:00.000-0500");
String strDate = parseFormat.format(date);
System.out.println(strDate);
// if you get date of type 'java.sql.Date' directly from database cursor like
//rs.getDate("created_date"), just pass it directly to format()
SimpleDateFormat dateFormat = new SimpleDateFormat(
"dd-MMM-yyyy HH:mm:ss");
String stringDate = dateFormat.format(date);
System.out.println(stringDate);
}
}
/*
Output:
2012-03-16T01:00:00.000-0400
16-Mar-2012 01:00:00
*/
you can also convert java.util.Date to java.sql.Date like this,
String dateString = "03-11-2012";
SimpleDateFormat dateFormat = new SimpleDateFormat("MM-dd-yyyy");
java.util.Date date = dateFormat.parse(dateString);
java.sql.Date sqlDate = new Date(date.getTime());
// set the input param type as OracleTypes.DATE and pass the input param date as sqlDate
If you want to read in the date "2012-02-16T00:00:00.000-0500" you should probably use a SimpleDateFormat to parse it like so:
DateFormat parseFormat = new SimpleDateFormat(
"yyyy-MM-dd'T'HH:mm:ss.SSSZ");
Date date = parseFormat.parse("2012-02-16T00:00:00.000-0500");
Along with the rest of your code this writes:
16-Feb-2012 05:00:00
The parse format pattern letters are listed in the SimpleDateFormat documentation. The T is escaped with apostrophes.
This answer assumes Java 7, or you would be using the new date & time API from Java 8

how to convert string into date? JAVA

I have this string: 7 -Jun- 2014.
I want to convert to java.utils.Date;
I use this Code
SimpleDateFormat formatter = new SimpleDateFormat("dd/MM/yyyy");
String dateInString = "7-Jun-2013";
try {
Date date = formatter.parse(dateInString);
System.out.println(date);
System.out.println(formatter.format(date));
} catch (ParseException e) {
e.printStackTrace();
}
but I get this exception :
java.text.ParseException: Unparseable date: "7-Jun-2013"
at java.text.DateFormat.parse(Unknown Source)
at ma.abcsolution.util.Test.main(Test.java:15)
try using
SimpleDateFormat formatter = new SimpleDateFormat("dd-MMM-yyyy");
the SimpleDateFormat look at the given string like it you tell it to, so in your example it look for a string with 2 chars for days, followed by a '/' sign and then 2 chars for month and so on
Using SimpleDateFormatter you can convert from date string to date and date to date String
public final class DateUtil {
private static final String DEFAULT_DATE_FORMAT = "dd-MMM-yyyy";
private DateUtil() {
}
public static final String formatDate(final Date date, final String dateFormat) {
DateFormat format = new SimpleDateFormat(dateFormat, Locale.ENGLISH);
return format.format(date);
}
public static final Date formatDate(final String date) throws ParseException {
return formatDate(date, DEFAULT_DATE_FORMAT);
}
public static final Date formatDate(final String date, final String dateFormat) throws ParseException {
DateFormat format = new SimpleDateFormat(dateFormat);
return format.parse(date);
}
}
Whenever you are going yo format date please verify the format you are using
In your case you used dd/MM/yyyy but date you used in format dd-MMM-yyyy.
Use
SimpleDateFormat formatter = new SimpleDateFormat("dd-MMM-yyyy");
to format the date. You used the wrong format with the / signs.
See also:
http://docs.oracle.com/javase/7/docs/api/java/text/DateFormat.html
http://docs.oracle.com/javase/7/docs/api/java/text/SimpleDateFormat.html
Date date = new SimpleDateFormat("d-MMM-yyyy").parse("7-Jun-2014");
Use this code. It is simple.
import java.text.SimpleDateFormat;
import java.util.Date;
public class DateTime {
public static void main(String args[]){
SimpleDateFormat ft = new SimpleDateFormat("dd/MM/yyyy");
String dateInString = "7-Jun-2013";
Date date=new Date(dateInString);
System.out.println(ft.format(date));
}
}

Categories