Jjreina
Jjreina

Reputation: 2713

set calendar object hour to 0

this is my code

    TimeZone timeZone = TimeZone.getTimeZone("UTC");
    Calendar calendar = Calendar.getInstance(timeZone);
    calendar.set(Calendar.MINUTE, 0);
    calendar.set(Calendar.SECOND, 0);
    calendar.set(Calendar.MILLISECOND, 0); 
    calendar.set(Calendar.HOUR_OF_DAY, 0);
    Timestamp start = new Timestamp(calendar.getTime().getTime());

but the timestamp result is for instance = 2014-09-30 02:00:00.0 I´m not able to set the hours to 0.

Any suggestions.

Upvotes: 2

Views: 185

Answers (2)

icza
icza

Reputation: 417472

Once you call Calendar.getTime() you get a Date object which is an instant in time which has no timezone info.

When you want to print or present this instance, the formatter will use the default time zone if not explicitly specified, which in your case is not UTC but maybe CET.

When you convert this instant to a String, you also have to tell in which timezone you want it to present. You have to specify UTC timezone there as well.

For example if using SimpleDateFormat, you can use its setTimeZone() method.

SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.S");
sdf.setTimeZone(TimeZone.getTimeZone("UTC"));

System.out.println(sdf.format(start));

Also if your result is from your database, you have to use a timestamp SQL type without timezone or with the UTC timezone.

Upvotes: 2

Christophe Dufour
Christophe Dufour

Reputation: 165

I guest icza is right.

To be sure, try this :

Timestamp start = new Timestamp(calendar.getTime().getTime());
System.out.println(start.getTimezoneOffset());

Upvotes: 1

Related Questions