dcsimg
 

Submitted by: Octavia Anghel(octaviaanghel@gmail.com)

Wednesday Jun 6th 2018 by Octavia Anghel

Language: Java, Expertise: Beginner - See why you shouldn't rely on the default time zone for your application.

Calendar calendar = new GregorianCalendar();
calendar.setTime(date);
calendar.set(Calendar.HOUR_OF_DAY, 0);
calendar.set(Calendar.MINUTE, 0);
calendar.set(Calendar.SECOND, 0);
Date startOfDay = calendar.getTime();

The code above calculates the start of the day (0h00). The first mistake is the missing millisecond field of the Calendar, but a major mistake is not setting the TimeZone of the Calendar object, as a result, the Calendar will use the default time zone. In a Desktop application this might be fine, but in server-side code this is a big problem. As an example, 0h00 in Tokyo is in a very different moment than in New York, so the developer should check which time zone is relevant for this computation.

Calendar calendar = new GregorianCalendar(user.getTimeZone());
calendar.setTime(date);
calendar.set(Calendar.HOUR_OF_DAY, 0);
calendar.set(Calendar.MINUTE, 0);
calendar.set(Calendar.SECOND, 0);
calendar.set(Calendar.MILLISECOND, 0);
Date startOfDay = calendar.getTime();
Home
Mobile Site | Full Site