Java format yyyy-MM-dd'T'HH:mm:ss.SSSz to yyyy-mm-dd HH:mm:ss

JavaParsingDateSimpledateformat

Java Problem Overview


I'm trying to format a date in yyyy-MM-dd'T'HH:mm:ss.SSSz format to yyyy-mm-dd HH:mm:ss, which should be easy but I can't get it to work.

A date that has to be parsed is in the form of: 2012-10-01T09:45:00.000+02:00
Now i use this simple date formatter to format it:

SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSz", Locale.FRANCE);

yet this gives an output similar to 2012-10-01T09:45:00.000UTC+00:00.

I've also tried to use "yyyy-MM-dd'T'HH:mm:ss.SSSZ" as pattern and "yyyy-MM-ddHH:mm:ss". The latter returns a date in the form of 2012-10-01T09:45:00 close, but not there yet.

I figured substringing the T away would be a bit messy and creates overhead for no reason, thus what would be the proper way to format these dates?

To illustrate I would like to convert 2012-10-01T09:45:00.000+02:00 into 2012-10-01 09:45:00

Cheers!

Java Solutions


Solution 1 - Java

SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
SimpleDateFormat output = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date d = sdf.parse(time);
String formattedTime = output.format(d);

This works. You have to use two SimpleDateFormats, one for input and one for output, but it will give you just what you are wanting.

Solution 2 - Java

java.time

We have new technology for this problem: the java.time framework built into Java 8 and later.

Your input string is in standard ISO 8601 format. That standard is used by default in the java.time classes for parsing/generating textual representations of date-time values.

OffsetDateTime odt = OffsetDateTime.parse( "2012-10-01T09:45:00.000+02:00" );

Your Question suggests you want to truncate to a whole second.

OffsetDateTime odtTruncatedToWholeSecond = odt.truncatedTo( ChronoUnit.SECONDS );

It seems you want to omit the offset and time zone info. The pre-defined formatter DateTimeFormatter.ISO_LOCAL_DATE_TIME does that.

And apparently you want to use a space in the middle rather than the standard T. You could define your own formatter for this, but I would just do a string manipulation to replace the T with a SPACE.

String output = odtTruncatedToWholeSecond.format( DateTimeFormatter.ISO_LOCAL_DATE_TIME ).replace( "T" , " " );

Simply String Manipulations

As the comments on the Question suggest, strictly speaking you can accomplish your goal by working only with strings and not converting to any date-time objects. But I provide this Answer here assuming you may have other business logic to work with these date-time values.


Table of date-time types in Java, both modern and legacy


About java.time

The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.

The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.

To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.

You may exchange java.time objects directly with your database. Use a JDBC driver compliant with JDBC 4.2 or later. No need for strings, no need for java.sql.* classes.

Where to obtain the java.time classes?

Table of which java.time library to use with which version of Java or Android

The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.

Solution 3 - Java

Gooye if it's possible to use Joda Time in your project then this code works for me:

String dateStr = "2012-10-01T09:45:00.000+02:00";
String customFormat = "yyyy-MM-dd HH:mm:ss";

DateTimeFormatter dtf = ISODateTimeFormat.dateTime();
LocalDateTime parsedDate = dtf.parseLocalDateTime(dateStr);
   
String dateWithCustomFormat = parsedDate.toString(DateTimeFormat.forPattern(customFormat));
System.out.println(dateWithCustomFormat);

Solution 4 - Java

I was trying to format the date string received from a JSON response e.g. 2016-03-09T04:50:00-0800 to yyyy-MM-dd. So here's what I tried and it worked and helped me assign the formatted date string a calendar widget.

String DATE_FORMAT_I = "yyyy-MM-dd'T'HH:mm:ss";
String DATE_FORMAT_O = "yyyy-MM-dd";


SimpleDateFormat formatInput = new SimpleDateFormat(DATE_FORMAT_I);
SimpleDateFormat formatOutput = new SimpleDateFormat(DATE_FORMAT_O);

Date date = formatInput.parse(member.getString("date"));
String dateString = formatOutput.format(date);

This worked. Thanks.

Solution 5 - Java

Try This

SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");

SimpleDateFormat output = new SimpleDateFormat("yyyyMMddHHmmss");

Date d = sdf.parse("2021-09-23T22:05:18.884Z");

String formattedTime = output.format(d);

System.out.println(formattedTime);

Results : 20210923220518

Solution 6 - Java

If you really gotta be fast (not that I believe you do):

char[] chars = sourceDate.toCharArray();
chars[10] = ' ';
String targetDate = new String(chars, 0, 19);

Solution 7 - Java

String dateStr = "2016-09-17T08:14:03+00:00";
String s = dateStr.replace("Z", "+00:00");
s = s.substring(0, 22) + s.substring(23);
Date date = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ").parse(s);
Timestamp createdOn = new Timestamp(date.getTime());
mcList.setCreated_on(createdOn);

Java 7 added support for time zone descriptors according to ISO 8601. This can be use in Java 7.

Solution 8 - Java

I have a case where I am transforming a legacy DB2 z/os database timestamp (formatted as: "yyyy-MM-dd'T'HH:mm:ss.SSSZ") into a SqlServer 2016 datetime2 (formatted as: "yyyy-MM-dd HH:mm:ss.SSS) field that is handled by our Spring/Hibernate Entity Manager instance (in this case, the OldRevision Table). In the Class, I define the date as the java.util type, and write the setter and getter in the normal way. Then, When handling the data, the code I have handling the data related to this question looks like this:

OldRevision revision = new OldRevision();
String oldRevisionDateString= oldRevisionData.getString("originalRevisionDate", "");
Date oldDateFormat = new SimpleDateFormat("yyyy-MM-dd'T'hh:mm:ss.SSSZ");
oldDateFormat.parse(oldRevisionDateString);
SimpleDateFormat newDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
newDateFormat.setTimeZone(TimeZone.getTimeZone("EST"));
Date finalFormattedDate= newDateFormat.parse(newDateFormat.format(oldDateFormat));
revision.setOriginalRevisionDate(finalFormattedDate);
em.persist(revision);

A simpler way to do the same case is:

SimpleDateFormat newDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
newDateFormat.setTimeZone(TimeZone.getTimeZone("EST"));
revision.setOriginalRevisionDate(
		newDateFormat.parse(newDateFormat.format(
				new SimpleDateFormat("yyyy-MM-dd'T'hh:mm:ss.SSSZ")
						.parse(rs.getString("originalRevisionDate", "")))));

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionGooeyView Question on Stackoverflow
Solution 1 - JavactleviView Answer on Stackoverflow
Solution 2 - JavaBasil BourqueView Answer on Stackoverflow
Solution 3 - JavamoleksyukView Answer on Stackoverflow
Solution 4 - JavaKiran MadanwadView Answer on Stackoverflow
Solution 5 - JavacodeAmanView Answer on Stackoverflow
Solution 6 - JavaHot LicksView Answer on Stackoverflow
Solution 7 - JavaSangram BadiView Answer on Stackoverflow
Solution 8 - Javajim owensView Answer on Stackoverflow