Java String to DateTime
Asked Answered
W

5

20

I have a string from a json response:

start: "2013-09-18T20:40:00+0000",
end: "2013-09-18T21:39:00+0000",

How do i convert this string to a java DateTime Object?

i have tried using the following:

SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSXXX");
start = sdf.parse("2013-09-18T20:40:00+0000");

but with this i can only create a Date Object. But the time binded in the String is kinda essential.

Any Help is greatly appreciated!

Weese answered 16/9, 2013 at 8:33 Comment(6)
Date also has time information.Hypomania
Ok, but still i need it to be a DateTime Object :)Weese
Java has no DateTime class. Use Date.Hypomania
Are you talking about java api or the joda time api?Whiteness
FYI, the troublesome old date-time classes such as java.util.Date, java.util.Calendar, and java.text.SimpleDateFormat are now legacy, supplanted by the java.time classes built into Java 8 and later. See Tutorial by Oracle.Masked
Similar to Generic support for ISO 8601 format in Java 6.Faydra
A
9

You can create Joda DateTime object from the Java Date object, since Java does not have a DateTime class.

DateTime dt = new DateTime(start.getTime());

Though the Date class of Java holds the time information as well(that's what you need in the first place), I suggest you to use a Calendar instead of the Date class of Java.

Calendar myCal = new GregorianCalendar();
myCal.setTime(date);

Have a look at the Calendar docs for more info on how you can use it more effectively.


Things have changed and now even Java (Java 8 to be precise), has a LocalDateTime and ZonedDateTime class. For conversions, you can have a look at this SO answer(posting an excerpt from there).

Given: Date date = [some date]

(1) LocalDateTime << Instant<< Date

Instant instant = Instant.ofEpochMilli(date.getTime());
LocalDateTime ldt = LocalDateTime.ofInstant(instant, ZoneOffset.UTC);

(2) Date << Instant << LocalDateTime

Instant instant = ldt.toInstant(ZoneOffset.UTC);
Date date = Date.from(instant);
Anglicanism answered 16/9, 2013 at 8:36 Comment(3)
+1 for the use of Joda - it's a far better date implementation as the basic Java oneSibelle
@RJ Your link points to the wrong Date, it's java.util.Date, not java.sql.Date :)Hagfish
LocalDateTime is the wrong type to use here. You would be throwing away valuable time zone or offset-from-UTC information. Use ZonedDateTime when you want to view an Instant in another region’s wall-clock time.Masked
H
10

You don't need a DateTime object. java.util.Date stores the time too.

int hours = start.getHours(); //returns the hours
int minutes = start.getMinutes(); //returns the minutes
int seconds = start.getSeconds(); //returns the seconds

As R.J says, these methods are deprecated, so you can use the java.util.Calendar class:

Calendar calendar = Calendar.getInstance();
calendar.setTime(sdf.parse("2013-09-18T20:40:00+0000"));
int hour = calendar.get(Calendar.HOUR); //returns the hour
int minute = calendar.get(Calendar.MINUTE); //returns the minute
int second = calendar.get(Calendar.SECOND); //returns the second

Note: on my end, sdf.parse("2013-09-18T20:40:00+0000") fires a

java.text.ParseException: Unparseable date: "2013-09-18T20:40:00+0000"
    at java.text.DateFormat.parse(DateFormat.java:357)
    at MainClass.main(MainClass.java:16)
Hagfish answered 16/9, 2013 at 8:37 Comment(0)
A
9

You can create Joda DateTime object from the Java Date object, since Java does not have a DateTime class.

DateTime dt = new DateTime(start.getTime());

Though the Date class of Java holds the time information as well(that's what you need in the first place), I suggest you to use a Calendar instead of the Date class of Java.

Calendar myCal = new GregorianCalendar();
myCal.setTime(date);

Have a look at the Calendar docs for more info on how you can use it more effectively.


Things have changed and now even Java (Java 8 to be precise), has a LocalDateTime and ZonedDateTime class. For conversions, you can have a look at this SO answer(posting an excerpt from there).

Given: Date date = [some date]

(1) LocalDateTime << Instant<< Date

Instant instant = Instant.ofEpochMilli(date.getTime());
LocalDateTime ldt = LocalDateTime.ofInstant(instant, ZoneOffset.UTC);

(2) Date << Instant << LocalDateTime

Instant instant = ldt.toInstant(ZoneOffset.UTC);
Date date = Date.from(instant);
Anglicanism answered 16/9, 2013 at 8:36 Comment(3)
+1 for the use of Joda - it's a far better date implementation as the basic Java oneSibelle
@RJ Your link points to the wrong Date, it's java.util.Date, not java.sql.Date :)Hagfish
LocalDateTime is the wrong type to use here. You would be throwing away valuable time zone or offset-from-UTC information. Use ZonedDateTime when you want to view an Instant in another region’s wall-clock time.Masked
P
7

You can use DateTimeFormatter

DateTimeFormatter format = DateTimeFormat.forPattern("yyyy-MM-dd'T'HH:mm:ss.SSSXXX");
DateTime time = format.parseDateTime("2013-09-18T20:40:00+0000");
Picaresque answered 16/9, 2013 at 8:53 Comment(2)
This support is there from Android O onwardsMeredi
No, @PrasadGKulkarni, it’s Joda-Time, an external library that works fine with earlier Android versions too.Faydra
F
1

java.time

I recommend that you use java.time, the modern Java date and time API, for your date and time work.

    String startStr = "2013-09-18T20:40:00+0000";
    OffsetDateTime start = OffsetDateTime.parse(startStr, isoFormatter);
    System.out.println(start);

Output is:

2013-09-18T20:40Z

I was using this formatter:

private static final DateTimeFormatter isoFormatter = new DateTimeFormatterBuilder()
        .append(DateTimeFormatter.ISO_LOCAL_DATE_TIME)
        .appendOffset("+HHMM", "+0000")
        .toFormatter();

If by a DateTime object you meant org.joda.time.Datetime, please read this quote from the Joda-Time homepage (boldface is original):

Note that from Java SE 8 onwards, users are asked to migrate to java.time (JSR-310) - a core part of the JDK which replaces this project.

The SimpleDateFormat class that you tried to use in the question is a notorious troublemaker of a class and long outdated. Under no circumstances use it. Ever.

Links

Faydra answered 16/2, 2021 at 20:59 Comment(0)
M
-1

Have you try this?

Date date1=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse("2013-09-18T20:40:00+0000".replace("T"," ").substring(0,19));
Mathi answered 3/5, 2021 at 13:13 Comment(1)
Unnecessary replace functionOry

© 2022 - 2025 — McMap. All rights reserved.