Shaik Mujahid Ali
Shaik Mujahid Ali

Reputation: 2378

Date formatter in java 8

I have a requirement where i have to store different date and time with time zones. I have used ZonedDateTime of java 8 .

ZoneId zoneId = ZoneId.of("US/Eastern");
ZonedDateTime zt = ZonedDateTime.now(zoneId);

System.out.println(zt.toString());

My problem is I want to store this in java.util.Date format. I used DateTimeFormatter

 DateTimeFormatter dtf=DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ssZ");
dtf.format(zt);

Until here it works fine this gives me the required date in string format now when i try to convert this to java.util.Date using simple date format

SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ");
System.out.println(sdf.parse(dtf.format(zt)));

I get output as Sat Mar 12 00:44:10 IST 2016 but i want output as 2016-03-11T14:14:10-05:00 in java.util.Date type. Can somebody suggest where am i going wrong?

Upvotes: 3

Views: 21971

Answers (2)

Basil Bourque
Basil Bourque

Reputation: 339193

ZonedDateTime > Instant > Date

Best to avoid the old date-time classes including java.util.Date. But if you must, you can convert. Call the new from method on the old java.util.Date class.

For that you need an Instant a moment on the timeline in UTC.

Instant instant = myZonedDateTime.toInstant();
java.util.Date juDate = java.util.Date.from( instant );

To go the other direction:

Instant instant = juDate.toInstant();

Upvotes: 2

Raghu K Nair
Raghu K Nair

Reputation: 3942

You are using a wrong way this is the corrected code

sdf.format(sdf.parse(val)) this the right way.

    ZoneId zoneId = ZoneId.of("US/Eastern");
    ZonedDateTime zt = ZonedDateTime.now(zoneId);

    System.out.println(zt.toString());
    DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ssZ");
    String val = dtf.format(zt);
    System.out.println(val);

    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ");
    //String dateStr = zt.format(sdf);
    System.out.println(sdf.format(sdf.parse(val)));

Upvotes: 4

Related Questions