Amir Rachum
Amir Rachum

Reputation: 79645

Creating a GregorianCalendar instance from milliseconds

I have a certain time in milliseconds (in a Timestamp object) and I want to use it to create a GregorianCalendar object. How can I do that?

EDIT: How do I do the reverse?

Upvotes: 27

Views: 55935

Answers (4)

haaduken
haaduken

Reputation: 664

To get a GregorianCalendar object and not a Calendar object. Like Michael's answer provides, you can also do the following:

long timestamp = 1234567890;
GregorianCalendar cal = new GregorianCalendar();
cal.setTimeInMillis(timestamp);

This assumes a UTC epoch timestamp.

Upvotes: 47

Michael Konietzka
Michael Konietzka

Reputation: 5499

Just get an instance of GregorianCalendar and setTime with your java.sql.Timestamp timestamp:

Calendar cal=GregorianCalendar.getInstance();
cal.setTime(timestamp);

Edit: As peterh pointed out, GregorianCalendar.getInstance() will not provide a GregorianCalendar by default, because it is inherited fromCalendar.getInstance(), which can provide for example a BuddhistCalendar on some installations. To be sure to use a GregorianCalender use new GregorianCalendar() instead.

Upvotes: 45

stark
stark

Reputation: 839

I believe this works, although it may not be the best approach:

import java.sql.Date;
import java.sql.Timestamp;
import java.util.GregorianCalendar;

public class TimestampToGregorianCalendar {

    /**
     * @param args
     */
    public static void main(String[] args) {
        Timestamp t = new Timestamp(12356342); // replace with existing timestamp
        Date d = new Date(t.getTime());
        Calendar gregorianCalendar = GregorianCalendar.getInstance();
        gregorianCalendar.setTime(d);
    }

}

Upvotes: 1

aepryus
aepryus

Reputation: 4825

Timestamp timestamp = new Timestamp(23423434);
Calendar calendar = GregorianCalendar.getInstance();
calendar.setTimeInMillis(timestamp.getTime());

Upvotes: 11

Related Questions