Si configuro horas, minutos y segundos a 0 en una fecha, el día disminuye en uno.

En primer lugar, sé que puedo usar Calendar, but I want to understand this problem and learn to solve it.

Tengo un Date with the current date. I want to set hours, minutes and seconds to 0. I do it with this code:


Something is going wrong because if I do that, the day gets decreased by 1, for example, if today is 31, the day gets set to 30.

why? How can it be solved with Date (sin uso Calendar, I want to learn how to solve this problem by the hard way). Thanks

preguntado el 31 de julio de 12 a las 13:07

@LukeTaylor Why not? There are plenty of potentially valid question titles that include the word "why". -

Your question title is legit now, it was all kangfu before that. :P -

This code does not change the day; ? -

day is not changing for me..And why to use depricated methods if option is available.. -

Is this issue constrained to android devices, since the java.util.Date does not replicate this (as per the link in my previous comment)? -

2 Respuestas

Solo adivinando...

I guess it has to do with 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 resulting date is not:



0:0:0 GMT

and that's a day before if you are on America.

Try to set minutes to -yourDate.getTimezoneOffset() (try with positive value if it doesn't work).

Respondido 31 Jul 12, 13:07

Look at the implementation of these methods. They use a gregorian calendar. The error might come from that interaction.

Note: The set methods are all deprecated since JDK 1.1 ver

Respondido 31 Jul 12, 13:07

If that's true, it's a convention that makes absolutely no sense. - antonio grist

try to set the hours, minutes and seconds to zero. Check if decrementing the long (0:00:00 to 23:59:59) is resulting in a smaller day. - RaphMclee

I can't replicate the situation being described in the question, personally. Initialising a Date object gives me the time at which it was initialised, calling setHours(0), setMinutes(0) y setSeconds(0) provides me with a Date object that's midnight today, then subtracting 1000 from the long value (a second earlier) gives me a Date that's 23:59:59 yesterday. - antonio grist

@AndroidUser99: How to solve? Do not use deprecated methods if there is already an alternative. All the methods in Date were deprecated for a reason - they do not work properly (the Javadoc is quite clear about that). - Durandal

yes but i want to understan a way to solve this with date, only for learn it - Excepción de puntero nulo

No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas or haz tu propia pregunta.