Java - How to convert this string to date?

I am receiving this from the server and I don´t understand what the T and Z means, 2012-08-24T09:59:59Z What's the correct SimpleDateFormat pattern to convert this string to a Date object?

Upvotes: 2

Views: 9495

Answers (7)

brimborium
brimborium

Reputation: 9512

The Z stands for Zulu (UTC) and this is the dateTime.tz format (ISO-8601). So, you should be able to do something like this:

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

There is an example here: example

Upvotes: 2

BendaThierry.com
BendaThierry.com

Reputation: 2110

Maybe using the excellent joda time library to convert a String as a Date:

LocalDate myDate = new LocalDate("2012-08-28") // the constructor need an Object but is internally able to parse a String.

Upvotes: 0

Mohammod Hossain
Mohammod Hossain

Reputation: 4114

RSS 2.0 format string EEE, dd MMM yyyy HH:mm:ss z   
Example: Tue, 28 Aug 2012 06:55:11 EDT

Atom (ISO 8601) format string  yyyy-MM-dd'T'HH:mm:ssz
Example:2012-08-28T06:55:11EDT

try {
            String str_date = "2012-08-24T09:59:59Z";
            DateFormat formatter;
            Date date;
            formatter = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
            date = (Date) formatter.parse(str_date);
            System.out.println("Today is " + date);
        } catch (ParseException e) {
            System.out.println("Exception :" + e);
        } 

Upvotes: 2

Curious
Curious

Reputation: 2961

This is the ISO datetime format, see here, T is the time separator and Z is the zone designator for the zero UTC offset.

There is a very similar, if not identical question here, see it to know how to convert this string to a Java DateTime object.

Upvotes: 2

Ami
Ami

Reputation: 4259

// First parse string in pattern "yyyy-MM-dd'T'HH:mm:ss'Z'" to date object.

String dateString1 = "2012-08-24T09:59:59Z";
Date date = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'").parse(dateString1);

// Then format date object to string in pattern "MM/dd/yy 'at' h:mma".
String dateString2 = new SimpleDateFormat("MM/dd/yy 'at' h:mma").format(date);
System.out.println(dateString2); // 08/24/12 at 09:59AM

I think this might be useful to you.

Upvotes: -1

Sumit Neema
Sumit Neema

Reputation: 480

import org.joda.time.*;
import org.joda.time.format.*;

public class Test {
    public static void main(String[] args) {
        String text = "2012-08-24T09:59:59Z";
        DateTimeFormatter parser = ISODateTimeFormat.dateTime();
        DateTime dt = parser.parseDateTime(text);

        DateTimeFormatter formatter = DateTimeFormat.mediumDateTime();
        System.out.println(formatter.print(dt));
    }
}

or simply check that link str to date

Upvotes: 1

Chathuranga Chandrasekara
Chathuranga Chandrasekara

Reputation: 20906

This is ISO 8601 Standard. You may use

SimpleDateFormat simpleFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");

to convert this.

Upvotes: 8

Related Questions