Jayyrus
Jayyrus

Reputation: 13051

Timestamp to Date issue

I'm trying to create a function that convert a timestamp to Date object.

My problem is that using this online tools i reach correctly to convert timestamp to date but using java it doesn't convert correctly.

This is what i try:

public static Date getDateFromUUID(UUID uuid) {
    Calendar uuidEpoch = Calendar.getInstance(TimeZone.getTimeZone("UTC"));
    uuidEpoch.clear();
    uuidEpoch.set(1582, 9, 15, 0, 0, 0);
    long epochMillis = uuidEpoch.getTime().getTime();
    long time = (uuid.timestamp() / 10000L) + epochMillis;

    Calendar start = Calendar.getInstance(TimeZone.getTimeZone("UTC"));
    Calendar end = Calendar.getInstance(TimeZone.getTimeZone("UTC"));
    start.setTimeInMillis(time*1000);
    end.set(start.get(Calendar.YEAR), start.get(Calendar.MONTH), start.get(Calendar.DAY_OF_MONTH),0,0,0);
    return end.getTime();
}

I'm trying using that uuid: a261ae00-2a9c-11b2-ae56-bcee7be23398

it correctly converts to timestamp : 1406412000

Using this:

Calendar start = Calendar.getInstance(TimeZone.getTimeZone("UTC"));
Calendar end = Calendar.getInstance(TimeZone.getTimeZone("UTC"));
start.setTimeInMillis(time*1000);
end.set(start.get(Calendar.YEAR), start.get(Calendar.MONTH), start.get(Calendar.DAY_OF_MONTH),0,0,0);
return end.getTime();

I need to remove hours, minutes and seconds and take only years,months and days. but it convert timestamp to

Sat Jul 26 02:00:00 CEST 2014

Instead of

Sun Jul 27 00:00:00 CEST 2014

what could be my mistake?

Thanks!

Upvotes: 0

Views: 219

Answers (1)

John B
John B

Reputation: 32949

Your time zone if wrong. Notice that output is CEST but you set the calendar to UTC. The delta between these two is 2 hours. When you output the Date you need to set the timezone appropriately.

Upvotes: 2

Related Questions