Java – If I set hours, minutes, and seconds to 0 in the date, the day decreases by 1:

If I set hours, minutes, and seconds to 0 in the date, the day decreases by 1:… here is a solution to the problem.

If I set hours, minutes, and seconds to 0 in the date, the day decreases by 1:

First of all, I know I can use Calendar, but I want to understand the problem and learn to solve it.

I have a Date with the current date. I want to set the hour, minute, and second to 0. I implemented it with the following code:

        current_date.setHours(0);
        current_date.setMinutes(0);
        current_date.setSeconds(0);

Something went wrong because if I did this, the days were subtracted by 1, for example, if today was 31, the days would be set to 30.

Why? How to solve it with Date (without using Calendar, I would like to learn how to solve this problem in a hard way). Thanks

Solution

Just guessing….

I guess it has something to do with the time zone.

When you set HMS to 0, you are not setting them according to your time zone, but according to UTC (not 100% sure, but …). So the result date is not:

0:0:0 YOUR LOCAL

But

0:0:0 GMT

If you’re in the U.S., it’s the day before.

Try setting the minute to -yourDate.getTimezoneOffset() (if that doesn’t work, try using a positive value).

Related Problems and Solutions