0

On Java, I do

Date minDate = new Date(year,month,1);
Date maxDate = new Date(year,month,31); 

to filter orders from day 1 to 31. But for some months (that has 30 days) and for february that has less, this ends up finding orders from days 1,2, and even 3, of the next month.

How can I create a minDate and maxDate that span the entire month exactly?

These data values are read by mongodb on the other side, but I'd like to do this in the java side if possible.

Paprika
  • 402
  • 5
  • 18
  • The solution to this is very easy to get to using the `java.time` APIs. any reason you aren't using that? – ernest_k Oct 28 '20 at 20:06
  • Are you using `java.util.Date`? You might have an easier time with `java.time.LocalDate` or with Joda Time. – Alonso del Arte Oct 28 '20 at 20:07
  • (1) Don’t use `Date`. That class is poorly designed and long outdated. Use java.time. (2) Choose a time zone. The month neither ends nor begins at the same point in time in all time zones. (3) Use *half-open*: represent the month as the interval from the first moment of this month inclusive until the first moment of the next month *exclusive*. – Ole V.V. Oct 29 '20 at 03:11

1 Answers1

3

java.util.Date is deprecated, and with good reason. On my local Scala REPL:

scala> import java.util.Date
import java.util.Date

scala> new Date(120, 9, 1, 0, 0)
       ^
       warning: constructor Date in class Date is deprecated: see corresponding Javadoc 
for more information.
res3: java.util.Date = Thu Oct 01 00:00:00 EDT 2020

scala> new Date(120, 9, 31, 23, 59)
       ^
       warning: constructor Date in class Date is deprecated: see corresponding Javadoc 
for more information.
res4: java.util.Date = Sat Oct 31 23:59:00 EDT 2020

If you have JShell, you should see something similar.

Okay, so not the whole Date class is deprecatd, but almost all its constructors and several of its getters and setters. Maybe java.time.LocalDate will work better for you.

scala> import java.time.LocalDate
import java.time.LocalDate

scala> LocalDate.of(2020, 10, 1)
res5: java.time.LocalDate = 2020-10-01

scala> LocalDate.of(2020, 10, 31)
res6: java.time.LocalDate = 2020-10-31

See, no need to subtract 1900 from the year. Easy, breezy, beautiful.

Alonso del Arte
  • 1,005
  • 1
  • 8
  • 19