0

SCENARIO
I'm modifying an app, and have a shitty database which I cannot modify. In one of the cases I duplicate an entity I need to put today's date without time.

  • In the MySQL DataBase, field is a DateTime.
  • In the Java entity, field is a Timestamp

WHAT I'VE TRIED
According to this question this will be enough to get today's date at midnight:

Calendar c = new GregorianCalendar();
c.set(Calendar.HOUR_OF_DAY, 0);
c.set(Calendar.MINUTE, 0);
c.set(Calendar.SECOND, 0);

Then I just need to add it to my entity, as the Java field is a Timestamp I use Calendar::getTimeInMillis method:

mEntity.setDate(new Timestamp(c.getTimeInMillis()));

i also tried:

mEntity.setrDate(new Timestamp(c.getTime().getTime()));

PROBLEM
In my database I always get one more second:

2015-04-08 00:00:01

That causes bad sorting by Date in the querys. I'm sure I can easily find a workaround, but I don't want to mess more the code and I cannot see why is this happening. Maybe I'm doing something wrong? Or is this the normal behaviour?

Community
  • 1
  • 1
Jordi Castilla
  • 26,609
  • 8
  • 70
  • 109

1 Answers1

0

You should try resetting the millisecond :

c.set(Calendar.MILLISECOND, 0);
flafoux
  • 2,080
  • 1
  • 12
  • 13
  • **This is a workaround, not an answer to my question**... If this is needed why [this answer](http://stackoverflow.com/questions/9629636/get-todays-date-in-java/9629822#9629822) has so many votes? – Jordi Castilla Apr 08 '15 at 13:27
  • you retrieve time in milliseconds but if you don't set it to zero with millisecond precision, then it won't be zero (it's `00:00:00:NNN`, NNN being random), and perhaps because of "rounding", seconds is 1 not zero – flafoux Apr 08 '15 at 13:43