I need to create two date objects. If the current date and time is March 9th 2012 11:30 AM then
- date object d1 should be 9th March 20
Here is a Java 8 based solution, using the new java.time package (Tutorial).
If you can use Java 8 objects in your code, use LocalDateTime:
LocalDateTime now = LocalDateTime.now(); // current date and time
LocalDateTime midnight = now.toLocalDate().atStartOfDay();
If you require legacy dates, i.e. java.util.Date:
Convert the LocalDateTime you created above to Date using these conversions:
LocalDateTime -> ZonedDateTime -> Instant -> Date
Call atZone(zone) with a specified time-zone (or ZoneId.systemDefault() for the system default time-zone) to create a ZonedDateTime object, adjusted for DST as needed.
ZonedDateTime zdt = midnight.atZone(ZoneId.of("America/Montreal"));
Call toInstant() to convert the ZonedDateTime to an Instant:
Instant i = zdt.toInstant()
Finally, call Date.from(instant) to convert the Instant to a Date:
Date d1 = Date.from(i)
In summary it will look similar to this for you:
LocalDateTime now = LocalDateTime.now(); // current date and time
LocalDateTime midnight = now.toLocalDate().atStartOfDay();
Date d1 = Date.from(midnight.atZone(ZoneId.systemDefault()).toInstant());
Date d2 = Date.from(now.atZone(ZoneId.systemDefault()).toInstant());
See also section Legacy Date-Time Code (The Java™ Tutorials) for interoperability of the new java.time functionality with legacy java.util classes.