Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert UTC Date String and remove the T and Z in Java?

Am using Java 1.7.

Trying to convert:

2018-05-23T23:18:31.000Z 

into

2018-05-23 23:18:31

DateUtils class:

public class DateUtils {

    public static String convertToNewFormat(String dateStr) throws ParseException {
        TimeZone utc = TimeZone.getTimeZone("UTC");
        SimpleDateFormat sdf = new SimpleDateFormat("YYYY-MM-dd HH:mm:ss");
        sdf.setTimeZone(utc);
        Date convertedDate = sdf.parse(dateStr);
        return convertedDate.toString();
    }
}

When trying to use it:

String convertedDate = DateUtils.convertToNewFormat("2018-05-23T23:18:31.000Z");
System.out.println(convertedDate);

Get the following exception:

Exception in thread "main" java.text.ParseException: Unparseable date: "2018-05-23T23:22:16.000Z"
   at java.text.DateFormat.parse(DateFormat.java:366)
   at com.myapp.utils.DateUtils.convertToNewFormat(DateUtils.java:7)

What am I possibly doing wrong?

Is there an easier way to do is (e.g. Apache Commons lib)?

like image 535
PacificNW_Lover Avatar asked May 23 '18 23:05

PacificNW_Lover


People also ask

How do I remove T and Z from timestamp?

To remove the T and Z characters from an ISO date in JavaScript, we first need to have the date in ISO format. If you don't have it already, you can convert it to ISO using the toISOString function on a Date object. This will get rid of both T and Z, resulting in "2022-06-22 07:54:52.657".

How do you convert UTC to Java?

Current UTC Time - Java 8 Instant * package for using the old java Date/Calendar classes. The Instant class defines a moment of the timeline in UTC as the default time zone. d1 = instant. toString();

What is T & Z in UTC time format?

The T is just a literal to separate the date from the time, and the Z means "zero hour offset" also known as "Zulu time" (UTC). If your strings always have a "Z" you can use: SimpleDateFormat format = new SimpleDateFormat( "yyyy-MM-dd'T'HH:mm:ss. SSS'Z'", Locale.US); format.

How do you convert Date to UTC format?

The ToUniversalTime method converts a DateTime value from local time to UTC. To convert the time in a non-local time zone to UTC, use the TimeZoneInfo. ConvertTimeToUtc(DateTime, TimeZoneInfo) method. To convert a time whose offset from UTC is known, use the ToUniversalTime method.

What is UTC time in Java?

UTC stands for Universal Time Coordinated (UTC). Before commence of UTC it was called Greenwich Mean Time (GMT). Indian users need to convert the IST time into UTC time when working in different time zones. In Java, there are many ways to get UTC time which are given below:

How to convert string to offsetdatetime in UTC in Java?

Parse String to OffsetDateTime in UTC Date time with offset information is represented in dd/MM/uuuu’T’HH:mm:ss:SSSXXXXX pattern. e.g. "03/08/2019T16:20:17:717+05:30". In this example, timestamp represents one instant at "+05:30" offset. Given below is a Java program to convert string to OffsetDateTime and get an equivalent instant in UTC.

How to convert string to zoneddatetime in UTC date time?

‘Z’ in string represents the UTC timezone. It is short form of Zulu and can be written as UTC +0:00. Program output. 3. Parse String to ZonedDateTime in UTC Date time with full zone information is represented in the following formats. dd/MM/uuuu’T’HH:mm:ss:SSSXXXXX pattern. e.g. "03/08/2019T16:20:17:717+05:30".

How to convert a string to date time in Java 8?

Learn to convert a string to date time instance classes e.g. ZonedDateTime or OffsetDateTime classes, using DateTimeFormatter class in Java 8. 1. Instant, OffsetDateTime and ZonedDateTime Classes In Java 8, OffsetDateTime, ZonedDateTime and Instant – all store an instant on the timeline to nanosecond precision.


2 Answers

tl;dr

Instant.parse( "2018-05-23T23:18:31.000Z" )                // Parse this String in standard ISO 8601 format as a `Instant`, a point on the timeline in UTC. The `Z` means UTC.
.atOffset( ZoneOffset.UTC )                                // Change from `Instant` to the more flexible `OffsetDateTime`.
.format(                                                   // Generate a String representing the value of this `OffsetDateTime` object.
    DateTimeFormatter.ofPattern( "uuuu-MM-dd HH:mm:ss" )   // Specify a formatting pattern as desired.
)                                                          // Returns a `String` object.

2018-05-23 23:18:31

ISO 8601

Your input string is in standard ISO 8601 format.

The java.time classes use these standard formats by default when parsing/generating strings.

The T separates the year-month-day portion from the hour-minute-second. The Z is pronounced Zulu and means UTC.

java.time

You are using troublesome old date-time classes that were supplanted years ago by the java.time classes. The Apache DateUtils is also no longer needed, as you will find its functionality in java.time as well.

Parse that input string as a Instant object. 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).

String input = "2018-05-23T23:18:31.000Z" ;
Instant instant = Instant.parse( input ) ;

To generate a string in another format, we need a more flexible object. The Instant class is meant to be a basic building block. Lets convert it to a OffsetDateTime`, using UTC itself as the specified offset-from-UTC.

OffsetDateTime odt = instant.atOffset( ZoneOffset.UTC ) ; 

Define a formatting pattern to match your desired output.

DateTimeFormatter f = DateTimeFormatter.ofPattern( "uuuu-MM-dd HH:mm:ss" ) ;
String output = odt.format( f ) ;

Tip: Consider using DateTimeFormatter::ofLocalized… methods to automatically localize the String generation per some Locale rather than hard-coding a formatting pattern.


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.

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

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

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. Hibernate 5 & JPA 2.2 support java.time.

Where to obtain the java.time classes?

  • Java SE 8, Java SE 9, Java SE 10, Java SE 11, and later - Part of the standard Java API with a bundled implementation.
    • Java 9 brought some minor features and fixes.
  • Java SE 6 and Java SE 7
    • Most of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport.
  • Android
    • Later versions of Android (26+) bundle implementations of the java.time classes.
    • For earlier Android (<26), a process known as API desugaring brings a subset of the java.time functionality not originally built into Android.
      • If the desugaring does not offer what you need, the ThreeTenABP project adapts ThreeTen-Backport (mentioned above) to Android. See How to use ThreeTenABP….
like image 138
Basil Bourque Avatar answered Nov 08 '22 11:11

Basil Bourque


Try this. You have to use one pattern for parsing and another for formatting.

public static String convertToNewFormat(String dateStr) throws ParseException {
    TimeZone utc = TimeZone.getTimeZone("UTC");
    SimpleDateFormat sourceFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
    SimpleDateFormat destFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    sourceFormat.setTimeZone(utc);
    Date convertedDate = sourceFormat.parse(dateStr);
    return destFormat.format(convertedDate);
}
like image 24
J K Avatar answered Nov 08 '22 12:11

J K