0

I have a Date object that is using the method getTime to return the milliseconds since 1/1/1970.

invoiceDate.getTime();

These milliseconds are passed to a java.sql.Date constructor like so:

new java.sql.Date( invoiceDate.getTime() );

And the result is a date in yyyy-MM-dd format.

Now my question is this, is it possible that java.sql.Date can produce an off by one error? For example, say the invoiceDate is set to Thu Jul 02 00:00:00 CDT 2015, is it then possible that java.sql.Date produces 2015-07-01?

Kyle
  • 35
  • 9
  • Do you have some code that is producing an off by 1 error? Why do you suspect this may be possible? – Asaph Jul 09 '15 at 17:37
  • No code that i can see is causing this. QA at the place i work claims that this happened, however, I cannot reproduce the supposed off by one error. – Kyle Jul 09 '15 at 17:53

3 Answers3

1

No. Java date does not store timezone so your invoiceDate and the new date object are equal. It prints CDT in toString() because that is the timezone of your jvm

Also see the docs for Date.getTime()

Returns the number of milliseconds since January 1, 1970, 00:00:00 GMT represented by this Date object.

And the for Date(long)

Allocates a Date object and initializes it to represent the specified number of milliseconds since the standard base time known as "the epoch", namely January 1, 1970, 00:00:00 GMT.

6ton
  • 4,174
  • 1
  • 22
  • 37
0

No. However the it doesn't care about time zones, which can create some problems. Also be aware that months count from zero while days are from 1.

Astrogat
  • 1,617
  • 12
  • 24
0

The accepted Answer by 6ton is correct. The toString methods on java.util.Date and java.sql.Date silently apply your JVM’s current default time zone to the date-time value which is in UTC zone.

java.time

This is one of many reasons to avoid using the old java.util.Date/.Calendar and java.sql.Date. Try to do the bulk of your work using the new java.time framework in Java 8 and later, or the 3rd-party Joda-Time library.

If you truly only care about date without time-of-day, meaning your app will never leave one locality (time zone), then use a date-only class. The old date-time classes lack this. Both java.time and Joda-Time offer such a date-only class, both called LocalDate.

Using LocalDate this way has been discussed many times on StackOverflow. Please search for more info.


There actually is a time zone assigned deep in the java.util.Date source code, but it is ignored for most purposes. Confusing? Yes. Yet another reason to avoid these old classes.

Community
  • 1
  • 1
Basil Bourque
  • 303,325
  • 100
  • 852
  • 1,154