Geek
Geek

Reputation: 3329

date time conversion to specific format

I have a class file where the date field has value like "1329242400". This value in UI is represented as "0 day 00:02:56". I tried below but I get date in 1970's.

String attr = "1329242400";
Date cDate = new Date(Long.parseLong(attr));

Output is "Fri Jan 16 04:16:55 EST 1970"

Tried below,

GregorianCalendar c = new GregorianCalendar();
c.setTime(cDate);
XMLGregorianCalendar dDt = DatatypeFactory.newInstance().newXMLGregorianCalendar(c);

Output is "1970-01-16T04:16:55.200-05:00"

What other conversion method should I do to get "0 day 00:02:56" or like "Tue Feb 14 00:02:56 EST 2011"?

Upvotes: 0

Views: 649

Answers (3)

Arvind Kumar Avinash
Arvind Kumar Avinash

Reputation: 79550

java.time

Your string, "1329242400" is the number of seconds since the standard base time known as "the epoch", namely January 1, 1970, 00:00:00 GMT (or UTC). You can convert it into an Instant using Instant#ofEpochSecond which represents an instantaneous point on the timeline. It is independent of timezone (i.e. has a timezone offset of 00:00 hours, represented with Z in ISO 8601 standards).

You can convert Instant to a ZonedDateTime by applying the applicable ZoneId.

import java.time.Instant;
import java.time.ZoneId;
import java.time.ZonedDateTime;

public class Main {
    public static void main(String[] args) {
        Instant instant = Instant.ofEpochSecond(Long.parseLong("1329242400"));
        System.out.println(instant);

        ZonedDateTime zdt = ZonedDateTime.ofInstant(instant, ZoneId.of("America/New_York"));
        System.out.println(zdt);
    }
}

Output:

2012-02-14T18:00:00Z
2012-02-14T13:00-05:00[America/New_York]

Learn more about the the modern date-time API* from Trail: Date Time.


* 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.

Upvotes: 1

Churk
Churk

Reputation: 4637

GregorianCalendar c = new GregorianCalendar();
c.setTime(cDate);
XMLGregorianCalendar dDt = DatatypeFactory.newInstance().newXMLGregorianCalendar(c);

SimpleDateFormat sdf = new SimpleDateFormat ("E MM dd hh:mm:ss z");
sdf.format(c.getTime());

http://docs.oracle.com/javase/1.4.2/docs/api/java/text/SimpleDateFormat.html

Upvotes: 1

Marc B
Marc B

Reputation: 360842

The constructor expects the time stamp to be in milliseconds, so you're off by 3 orders of magnitude:

Date cDate = new Date(Long.parseLong(attr) * 1000);
                                           ^^^^^^

Upvotes: 2

Related Questions