1

I want to parse date of following type:

2010-07-13T17:27:00.000Z

How can i do it using simple date formatter in java? what format is to be used?

aks
  • 1,849
  • 8
  • 24
  • 21
  • For new readers to the question I recommend you don’t use `SimpleDateFormat`. That class is notoriously troublesome and long outdated. Instead use `Instant` from [java.time, the modern Java date and time API](https://docs.oracle.com/javase/tutorial/datetime/) and its `parse` method. – Ole V.V. Apr 29 '21 at 12:23

3 Answers3

5
  1. Take a look at the javadocs of SimpleDateFormat.
  2. Create an instance of this class, using the appropriate String in the constructor
  3. Call its parse method, passing in the String in your question
  4. ???
  5. Profit!

(You may notice that I'm not actually giving you the format string. This is a "teach a man to fish" answer. If you have problems working out specifically what you'd need to use for a particular section, then feel free to elaborate, stating what you tried and why it didn't work. But right now it sounds like you haven't got to the point of attempting any specific format strings. The Javadocs are reasonably well-written and contain everything you need. Being able to extract information from documentation is a massively important skill for a programmer and I'm not going to rob you of a chance to improve on it.)

Andrzej Doyle
  • 102,507
  • 33
  • 189
  • 228
1

The code should look like the following code.

For your date string "2010-07-13T17:27:00.000Z" you may try this format "yyyy-MM-dd'T'hh:mm:ss.S'Z'".

I assume the 'T' and 'Z' in your date string is constant/separator only.

import java.text.SimpleDateFormat;
import java.util.Date;

public class TestMain {

    public static void main(String[] args) throws Exception{

        String fromDateTime = "2010-12-01 00:01:23";
        DateFormat format = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss"); 
        Date date = null;

        date = format.parse(fromDateTime);
        //What ever you want to manipulate of this date object
        //... 

    }
}

EDIT: add proper class, method & comment to make it a complete program. Thanks for comment from @Andrzej Doyle. EDIT: remove throws IOException from the demo program. Thanks for @BalusC. EDIT: re-read the comment, got the full meaning of @BalusC :)

ttchong
  • 307
  • 2
  • 9
  • 2
    I'm really not keen on example bits of code that catch exceptions and merely print the stack trace. For the majority of applications, this is equivalent to simply swallowing the exception. The problem is that a simple copy-and-paste means that the code "works", so likely no attention is paid to the details of error handling. I **much** prefer code snippets that put this in a method and simply declare the method to throw the relevant Exception - this is both correct and forces copy-pasters to really think about what they want to do with the exception. (And if (*they* swallow it, so be it). – Andrzej Doyle Jul 16 '10 at 15:37
  • @Andrzej Doyle- for production code yes, you list one by one the discrete exception that you want to handle and ignore the one you don't care exactly. For quick demo or debugging code, personally I prefer to print whatever exception being throw simply because it causes me less key stroke to answer a question. During debug session, it is also easier for you to get a working code first before you start to care on those possible bad things to happen but you don't see it through out the time you spend with your code. Refactoring always has it beauty :) – ttchong Jul 16 '10 at 15:57
  • 1
    Replace `throws IOException` (was it a leftover? ;) ) by `throws Exception`, get rid of the `catch` blocks and it'll be fine. Let the "enduser" worry about exception handling himself. – BalusC Jul 16 '10 at 16:06
1

The date-time string, 2010-07-13T17:27:00.000Z complies with ISO 8601 date-time pattern. In this string, T is a separator for date and time and Z stands for Zulu which specifies UTC (i.e. a timezone offset of +00:00 hours). The format required to parse this date-time string is as follows:

yyyy-MM-dd'T'HH:mm:ss.SSSX 

Learn more about the pattern at the documentation page.

Note that the legacy date-time API (java.util date-time types and their formatting API, SimpleDateFormat) are outdated and error-prone. It is recommended to stop using them completely and switch to java.time, the modern date-time API* .

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.Instant;
import java.time.OffsetDateTime;
import java.time.ZonedDateTime;
import java.util.Date;
import java.util.TimeZone;

public class Main {
    public static void main(String args[]) throws ParseException {
        String strDateTime = "2010-07-13T17:27:00.000Z";

        Instant instant = Instant.parse(strDateTime);
        ZonedDateTime zdt = ZonedDateTime.parse(strDateTime);
        OffsetDateTime odt = OffsetDateTime.parse(strDateTime);

        System.out.println(instant);
        System.out.println(zdt);
        System.out.println(odt);

        // #################Using legacy API####################
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSX");
        Date date = sdf.parse(strDateTime);
        // Default format
        System.out.println(date);
        // Custom format
        sdf.setTimeZone(TimeZone.getTimeZone("Etc/UTC"));
        System.out.println(sdf.format(date));
        // #####################################################
    }
}

Output:

2010-07-13T17:27:00Z
2010-07-13T17:27Z
2010-07-13T17:27Z
Tue Jul 13 18:27:00 BST 2010
2010-07-13T17:27:00.000Z

Note that the default patterns in modern date-time follow ISO 8601 standard and there you do not need a DateTimeFormatter (the counterpart of SimpleDateFormat in the modern date-time API) explicitly in order to parse an ISO 8601 date-time string. Learn more about the modern date-time API from Trail: Date Time.

Another point important to be mentioned here is the java.util.Date object is not a real date-time object like the modern date-time types; rather, it represents the number of milliseconds since the standard base time known as "the epoch", namely January 1, 1970, 00:00:00 GMT (or UTC). When you print an object of java.util.Date, its toString method returns the date-time in the JVM's timezone, calculated from this milliseconds value. If you need to print the date-time in a different timezone, you will need to set the timezone to SimpleDateFormat and obtain the formatted string from it.


* For any reason, if you have to stick to Java 6 or Java 7, you can use ThreeTen-Backport which backports most of the java.time functionality to Java 6 & 7. If you are working for an Android project and your Android API level is still not compliant with Java-8, check Java 8+ APIs available through desugaring and How to use ThreeTenABP in Android Project.

Arvind Kumar Avinash
  • 71,965
  • 6
  • 74
  • 110