Change date format Java getting Unparseable date Error - java

I have a date in the following format:
lastUpdatedDate = "12/14/2021 09:15:17";
I used the following code/format to convert date into yyyy-MM-dd hh:mm:ss format:
SimpleDateFormat dt = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
Date lastUpdatedDateFormatted = dt.parse(lastUpdatedDate);
But it gives me below error:
java.text.ParseException: Unparseable date: "12/14/2021 09:15:17"
output should be: 2021-12-14 09:15:17
How can I achieve this?

Change the format to
SimpleDateFormat dt = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss");
Date lastUpdatedDateFormatted = dt.parse(lastUpdatedDate);
System.out.println(lastUpdatedDateFormatted);
And it should be able to parse the date then.

As you are wanting to display or output the date in yyyy-MM-dd HH:mm:ss format, you should parse the date first then format the date to desired format.
try {
String lastUpdatedDate = "12/14/2021 09:15:17";
Date lastDate = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss").parse(lastUpdatedDate);
System.out.println(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(lastDate));
} catch (ParseException e) {
e.printStackTrace();
}

Your formatting pattern fails to match your input string.
And you are using terrible date-time classes that were years ago supplanted by the modern java.time classes defined in JSR 310.
java.time
The modern solution uses the java.time classes.
Your input lacks an indicator of time zone or offset from UTC, so parse as a LocalDateTime object.
LocalDateTime ldt =
LocalDateTime
.parse(
"12/14/2021 09:15:17" ,
DateTimeFormatter.ofPattern( "MM/dd/uuuu hh:mm:ss" ) ;
) ;
Your desired output is nearly compliant with the ISO 8601 standard format used by default in java.time, except for that SPACE in the middle rather than T.
String output = ldt.toString().replace( "T" , " " ) ;

Related

Java, unparsable date error, converting from String to Date

I have this String "2019-10-17T16:00:00+02:00" and I want to convert this String to a Date object, because I want to change the format. I tried this:
SimpleDateFormat sd1 = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ");
Date dt = sd1.parse(mystring);
SimpleDateFormat sd2 = new SimpleDateFormat("yyyy-MM-dd");
String newDate = sd2.format(dt);
System.out.println(newDate);
But I have this message: Unparseable date: "2019-10-17T16:00:00+02:00"
What can I do?
Thank you all
For the sake of being up to date:
Please consider using the modern date and time API java.time.
You can easily parse and format dates, times and date times using it.
See this example:
public static void main(String[] args) {
String d = "2019-10-17T16:00:00+02:00";
OffsetDateTime odt = OffsetDateTime.parse(d, DateTimeFormatter.ISO_OFFSET_DATE_TIME);
System.out.println(odt.format(DateTimeFormatter.ofPattern("yyyy/MM/dd HH:mm:ss Z")));
}
The output is this:
2019/10/17 16:00:00 +0200
That formatter is used be default, so no need to specify. The standard ISO 8601 formats are used by default in java.time.
OffsetDateTime.parse( "2019-10-17T16:00:00+02:00" ) // ISO 8601 formats can be parsed directly, without specifying a `DateTimeFormatter` object.
If you just want to extract the date part of a date time, then you can do that, too by just applying two additional lines of code:
LocalDate date = odt.toLocalDate();
System.out.println(date.format(DateTimeFormatter.ISO_DATE));
The pattern letter for ISO 8601 time zones is X not Z as others have noted.
Use:
SimpleDateFormat sd1 = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssX");
And parsing will succeed.

convert string to instant with different time component formats [duplicate]

I have a java component to format the date that I retrieve. Here is my code:
Format formatter = new SimpleDateFormat("yyyyMMdd");
String s = "2019-04-23 06:57:00.0";
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-mm-dd hh:mm:ss.S");
try
{
Date date = simpleDateFormat.parse(s);
System.out.println("Formatter: "+formatter.format(date));
}
catch (ParseException ex)
{
System.out.println("Exception "+ex);
}
The code works great as long as the String s has the format "2019-04-23 06:57:00.0";
My Question is, how to tweak this code so it will work for below scenarios ex,
my s string may have values like
String s = "2019-04-23 06:57:00.0";
or
String s = "2019-04-23 06:57:00";
Or
String s = "2019-04-23";
right now it fails if I don't pass the ms.. Thanks!
Different types
String s = "2019-04-23 06:57:00";
String s = "2019-04-23";
These are two different kinds of information. One is a date with time-of-day, the other is simply a date. So you should be parsing each as different types of objects.
LocalDateTime.parse
To comply with the ISO 8601 standard format used by default in the LocalDateTime class, replace the SPACE in the middle with a T. I suggest you educate the publisher of your data about using only ISO 8601 formats when exchanging date-time values as text.
LocalDateTime ldt1 = LocalDateTime.parse( "2019-04-23 06:57:00".replace( " " , "T" ) ) ;
The fractional second parses by default as well.
LocalDateTime ldt2 = LocalDateTime.parse( "2019-04-23 06:57:00.0".replace( " " , "T" ) ) ;
See this code run live at IdeOne.com.
ldt1.toString(): 2019-04-23T06:57
ldt2.toString(): 2019-04-23T06:57
LocalDate.parse
Your date-only input already complies with ISO 8601.
LocalDate ld = LocalDate.parse( "2019-04-23" ) ;
See this code run live at IdeOne.com.
ld.toString(): 2019-04-23
Date with time-of-day
You can strip out the time-of-day from the date.
LocalDate ld = ldt.toLocalDate() ;
And you can add it back in.
LocalTime lt = LocalTime.parse( "06:57:00" ) ;
LocalDateTime ldt = ld.with( lt ) ;
Moment
However, be aware that a LocalDateTime does not represent a moment, is not a point on the timeline. Lacking the context of a time zone or offset-from-UTC, a LocalDateTime cannot hold a moment, as explained in its class JavaDoc.
For a moment, use the ZonedDateTime, OffsetDateTime, or Instant classes. Teach the publisher of your data to include the offset, preferably in UTC.
Avoid legacy date-time classes
The old classes SimpleDateFormat, Date, and Calendar are terrible, riddled with poor design choices, written by people not skilled in date-time handling. These were supplanted years ago by the modern java.time classes defined in JSR 310.
In case of you have optional parts in pattern you can use [ and ].
For example
public static Instant toInstant(final String timeStr){
final DateTimeFormatter formatter = DateTimeFormatter
.ofPattern("yyyy-MM-dd HH[:mm[:ss[ SSSSSSSS]]]")
.withZone(ZoneId.of("UTC"));
try {
return Instant.from(formatter.parse(timeStr));
}catch (DateTimeException e){
final DateTimeFormatter formatter2 = DateTimeFormatter
.ofPattern("yyyy-MM-dd")
.withZone(ZoneId.of("UTC"));
return LocalDate.parse(timeStr, formatter2).atStartOfDay().atZone(ZoneId.of("UTC")).toInstant();
}
}
cover
yyyy-MM-dd
yyyy-MM-dd HH
yyyy-MM-dd HH:mm
yyyy-MM-dd HH:mm:ss
yyyy-MM-dd HH:mm:ss SSSSSSSS

Timestamp string to timestamp in java

I have the following string "2015-04-02 11:52:00+02" and I need to parse it in Java to a Timestamp.
I tried all sorts of formats including
SimpleDateFormat mdyFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss+Z");
but nothing seems to work - I keep getting a ParseException
Can anyone help?
I need something like:
SimpleDateFormat mdyFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss+Z");
Timestamp t = new Timestamp(mdyFormat.parse("2015-04-02 11:52:00+02").getTime());
Try This
String str="2009-12-31 23:59:59 +0100";
/\
||
Provide Space while providing timeZone
SimpleDateFormat mdyFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss Z");
System.out.println(mdyFormat.parse(str));
Output
Fri Jan 01 04:29:59 IST 2010
java.sql.Timestamp objects don't have time zones - they are instants in time, like java.util.Date
So try this:
SimpleDateFormat mdyFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Timestamp t = new Timestamp(mdyFormat.parse("2015-04-02 11:52:00").getTime());
try "yyyy-MM-dd HH:mm:ssX"
Z stand for timezone in the following format: +0800
X stand for timezone in the following format: +08
Examples here
ISO 8601
Replace that SPACE in the middle with a T and you have a valid standard (ISO 8601) string format that can be parsed directly by either the Joda-Time library or the new java.time package built into Java 8 (inspired by Joda-Time). Search StackOverflow for hundreds of examples.
If using java.time, read my comment on Question about a bug when parsing hours-only offset value.
Example in Joda-Time 2.7.
String inputRaw = "2015-04-02 11:52:00+02";
String input = inputRaw.replace( " ", "T" );
DateTimeZone zone = DateTimeZone.forID( "America/Montreal" ); // Specify desired time zone adjustment.
DateTime dateTime = new DateTime( input, zone );

convert XMLGregorianCalendar to date i.e "MM/DD/YYYY hh:mm:ss AM"

I have a date in XMLGregorianCalendar format like "2013-05-16T09:54:13" which i have to convert to timestamp "MM/DD/YYYY hh:mm:ss AM" for inserting into oracle database table using java.
how can i do this in Java?
You can do this to return a Date:
calendar.toGregorianCalendar().getTime()
I found that code from this tutorial. From there, you can use a SimpleDateFormat to turn it into a string in the format you want.
But, if you're using JDBC to save the date in the database, you probably can pass in the Date directly with this method:
preparedStatement.setDate(colNum, myDate);
Here is more clear answer:
Get instance of Date from XMLGregorianCalendar instance:
Date date = xmlCalendar.toGregorianCalendar().getTime();
I found that code from Convert XMLGregorianCalendar to Date in Java
Format that Date instance with format "MM/dd/yyyy hh:mm:ss a", you will get MM/DD/YYYY hh:mm:ss AM format
DateFormat formatter = new SimpleDateFormat("MM/dd/yyyy hh:mm:ss a");
String formattedDate = formatter.format(date)
From Convert Date to String in Java
For inserting database you would do what Daniel suggested
If you want to insert your date on a database I would first do what Daniel suggested:
XMLGregorianCalendar xgc=<assume this is initialized>;
Date timestamp=xgc.toGregorianCalendar().getTime();
and later insert it through a PreparedStatement as Timestamp in milliseconds (Epoch time). That way you won't loose precision.
preparedStatement.setTimestamp(colNum,new Timestamp(timestamp.getTime()));
tl;dr
myPreparedStatement.setObject(
… ,
myXGC.toGregorianCalendar()
.toZonedDateTime()
) ;
java.time
The modern approach uses the java.time classes that supplanted the troublesome old classes Date, Calendar, and GregorianCalendar.
Convert from the legacy classes to java.time.
GregorianCalendar gc = myXGC.toGregorianCalendar() ;
ZonedDateTime zdt = gc.toZonedDateTime();
Pass date-time values to your database as date-time objects rather than as strings.
If your JDBC driver complies with JDBC 4.2 and later, you can deal directly with java.time types.
myPreparedStatement.setObject( … , zdt ) ;
If your driver is not yet compliant, convert briefly to a java.sql type.
myPreparedStatement.setTimestamp( … , java.sql.Timestamp.from ( zdt.toInstant() ) ) ;
Use the DateFormat class in Java. This should be helpful: http://docs.oracle.com/javase/6/docs/api/java/text/DateFormat.html
You can convert XMLGregorianCalendar to java.util.Date Object by using these two lines of code :-
Date date = xmlDate.toGregorianCalendar().getTime();
System.out.println("java.util.date :- " + date);
To convert to java.slq.Date Object use this code :-
long time = xmlDate.toGregorianCalendar().getTime().getTime();
java.sql.Date sqlDate = new java.sql.Date(time);
You can see complete example here
Please use the function below - just pass the XMLGregorianCalendar instance and date format you want (format example: "DD MMMM yyyy" -> 01 January 2017)
public String parseDate(String format,XMLGregorianCalendar XMLdate){
Date date = XMLdate.toGregorianCalendar().getTime();
DateFormat formatter = new SimpleDateFormat(format);
String formattedDate = formatter.format(date);
return formattedDate;
}
This returns java.util.Date:
java.util.Date tempDate = issueDate.toGregorianCalendar().getTime();

Convert java.util.Date to String

I want to convert a java.util.Date object to a String in Java.
The format is 2010-05-30 22:15:52
Convert a Date to a String using DateFormat#format method:
String pattern = "MM/dd/yyyy HH:mm:ss";
// Create an instance of SimpleDateFormat used for formatting
// the string representation of date according to the chosen pattern
DateFormat df = new SimpleDateFormat(pattern);
// Get the today date using Calendar object.
Date today = Calendar.getInstance().getTime();
// Using DateFormat format method we can create a string
// representation of a date with the defined format.
String todayAsString = df.format(today);
// Print the result!
System.out.println("Today is: " + todayAsString);
From http://www.kodejava.org/examples/86.html
Format formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String s = formatter.format(date);
Commons-lang DateFormatUtils is full of goodies (if you have commons-lang in your classpath)
//Formats a date/time into a specific pattern
DateFormatUtils.format(yourDate, "yyyy-MM-dd HH:mm:SS");
tl;dr
myUtilDate.toInstant() // Convert `java.util.Date` to `Instant`.
.atOffset( ZoneOffset.UTC ) // Transform `Instant` to `OffsetDateTime`.
.format( DateTimeFormatter.ISO_LOCAL_DATE_TIME ) // Generate a String.
.replace( "T" , " " ) // Put a SPACE in the middle.
2014-11-14 14:05:09
java.time
The modern way is with the java.time classes that now supplant the troublesome old legacy date-time classes.
First convert your java.util.Date to an Instant. The Instant class represents a moment on the timeline in UTC with a resolution of nanoseconds (up to nine (9) digits of a decimal fraction).
Conversions to/from java.time are performed by new methods added to the old classes.
Instant instant = myUtilDate.toInstant();
Both your java.util.Date and java.time.Instant are in UTC. If you want to see the date and time as UTC, so be it. Call toString to generate a String in standard ISO 8601 format.
String output = instant.toString();
2014-11-14T14:05:09Z
For other formats, you need to transform your Instant into the more flexible OffsetDateTime.
OffsetDateTime odt = instant.atOffset( ZoneOffset.UTC );
odt.toString(): 2020-05-01T21:25:35.957Z
See that code run live at IdeOne.com.
To get a String in your desired format, specify a DateTimeFormatter. You could specify a custom format. But I would use one of the predefined formatters (ISO_LOCAL_DATE_TIME), and replace the T in its output with a SPACE.
String output = odt.format( DateTimeFormatter.ISO_LOCAL_DATE_TIME )
.replace( "T" , " " );
2014-11-14 14:05:09
By the way I do not recommend this kind of format where you purposely lose the offset-from-UTC or time zone information. Creates ambiguity as to the meaning of that string’s date-time value.
Also beware of data loss, as any fractional second is being ignored (effectively truncated) in your String’s representation of the date-time value.
To see that same moment through the lens of some particular region’s wall-clock time, apply a ZoneId to get a ZonedDateTime.
ZoneId z = ZoneId.of( "America/Montreal" );
ZonedDateTime zdt = instant.atZone( z );
zdt.toString(): 2014-11-14T14:05:09-05:00[America/Montreal]
To generate a formatted String, do the same as above but replace odt with zdt.
String output = zdt.format( DateTimeFormatter.ISO_LOCAL_DATE_TIME )
.replace( "T" , " " );
2014-11-14 14:05:09
If executing this code a very large number of times, you may want to be a bit more efficient and avoid the call to String::replace. Dropping that call also makes your code shorter. If so desired, specify your own formatting pattern in your own DateTimeFormatter object. Cache this instance as a constant or member for reuse.
DateTimeFormatter f = DateTimeFormatter.ofPattern( "uuuu-MM-dd HH:mm:ss" ); // Data-loss: Dropping any fractional second.
Apply that formatter by passing the instance.
String output = zdt.format( f );
About java.time
The java.time framework is built into Java 8 and later. These classes supplant the troublesome old date-time classes such as java.util.Date, .Calendar, & java.text.SimpleDateFormat.
The Joda-Time project, now in maintenance mode, advises migration to java.time.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations.
Much of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport and further adapted to Android in ThreeTenABP (see How to use…).
The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time.
Altenative one-liners in plain-old java:
String.format("The date: %tY-%tm-%td", date, date, date);
String.format("The date: %1$tY-%1$tm-%1$td", date);
String.format("Time with tz: %tY-%<tm-%<td %<tH:%<tM:%<tS.%<tL%<tz", date);
String.format("The date and time in ISO format: %tF %<tT", date);
This uses Formatter and relative indexing instead of SimpleDateFormat which is not thread-safe, btw.
Slightly more repetitive but needs just one statement.
This may be handy in some cases.
Why don't you use Joda (org.joda.time.DateTime)?
It's basically a one-liner.
Date currentDate = GregorianCalendar.getInstance().getTime();
String output = new DateTime( currentDate ).toString("yyyy-MM-dd HH:mm:ss");
// output: 2014-11-14 14:05:09
It looks like you are looking for SimpleDateFormat.
Format: yyyy-MM-dd kk:mm:ss
In single shot ;)
To get the Date
String date = new SimpleDateFormat("yyyy-MM-dd", Locale.getDefault()).format(new Date());
To get the Time
String time = new SimpleDateFormat("hh:mm", Locale.getDefault()).format(new Date());
To get the date and time
String dateTime = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss", Locale.getDefaut()).format(new Date());
Happy coding :)
public static String formateDate(String dateString) {
Date date;
String formattedDate = "";
try {
date = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss",Locale.getDefault()).parse(dateString);
formattedDate = new SimpleDateFormat("dd/MM/yyyy",Locale.getDefault()).format(date);
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return formattedDate;
}
If you only need the time from the date, you can just use the feature of String.
Date test = new Date();
String dayString = test.toString();
String timeString = dayString.substring( 11 , 19 );
This will automatically cut the time part of the String and save it inside the timeString.
Here are examples of using new Java 8 Time API to format legacy java.util.Date:
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss:SSS Z")
.withZone(ZoneOffset.UTC);
String utcFormatted = formatter.format(date.toInstant());
ZonedDateTime utcDatetime = date.toInstant().atZone(ZoneOffset.UTC);
String utcFormatted2 = utcDatetime.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss:SSS Z"));
// gives the same as above
ZonedDateTime localDatetime = date.toInstant().atZone(ZoneId.systemDefault());
String localFormatted = localDatetime.format(DateTimeFormatter.ISO_ZONED_DATE_TIME);
// 2011-12-03T10:15:30+01:00[Europe/Paris]
String nowFormatted = LocalDateTime.now().toString(); // 2007-12-03T10:15:30.123
It is nice about DateTimeFormatter that it can be efficiently cached as it is thread-safe (unlike SimpleDateFormat).
List of predefined fomatters and pattern notation reference.
Credits:
How to parse/format dates with LocalDateTime? (Java 8)
Java8 java.util.Date conversion to java.time.ZonedDateTime
Format Instant to String
What's the difference between java 8 ZonedDateTime and OffsetDateTime?
The easiest way to use it is as following:
currentISODate = new Date().parse("yyyy-MM-dd'T'HH:mm:ss", "2013-04-14T16:11:48.000");
where "yyyy-MM-dd'T'HH:mm:ss" is the format of the reading date
output: Sun Apr 14 16:11:48 EEST 2013
Notes: HH vs hh
- HH refers to 24h time format
- hh refers to 12h time format
public static void main(String[] args)
{
Date d = new Date();
SimpleDateFormat form = new SimpleDateFormat("dd-mm-yyyy hh:mm:ss");
System.out.println(form.format(d));
String str = form.format(d); // or if you want to save it in String str
System.out.println(str); // and print after that
}
Let's try this
public static void main(String args[]) {
Calendar cal = GregorianCalendar.getInstance();
Date today = cal.getTime();
DateFormat df7 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
try {
String str7 = df7.format(today);
System.out.println("String in yyyy-MM-dd format is: " + str7);
} catch (Exception ex) {
ex.printStackTrace();
}
}
Or a utility function
public String convertDateToString(Date date, String format) {
String dateStr = null;
DateFormat df = new SimpleDateFormat(format);
try {
dateStr = df.format(date);
} catch (Exception ex) {
ex.printStackTrace();
}
return dateStr;
}
From Convert Date to String in Java
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String date = "2010-05-30 22:15:52";
java.util.Date formatedDate = sdf.parse(date); // returns a String when it is parsed
System.out.println(sdf.format(formatedDate)); // the use of format function returns a String
Date date = new Date();
String strDate = String.format("%tY-%<tm-%<td %<tH:%<tM:%<tS", date);
One Line option
This option gets a easy one-line to write the actual date.
Please, note that this is using Calendar.class and SimpleDateFormat, and then it's not
logical to use it under Java8.
yourstringdate = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(Calendar.getInstance().getTime());

Categories