Using java Calendar how can you combine the start date, day and starttime?
For example:
If the start date is 9/8/2020. The day is 2 and the start time is 8:00 AM then how can we obtain a java date that is 9/9/2020 8:00 AM. Here is my unsuccessful attempt.
def startDateTime(Date startDate, int day, java.sql.Time startTime){
def date
date = Calendar.getInstance()
date.setTime(startDate)
//adding day. since day 1 is the first day we need to add day - 1
date.add(Calendar.DATE, day - 1)
// setting the time from startTime
date.setTimeInMillis(startTime.getTime())
return date.getTime()
}
Thanks for the help.
You are calling
date.setTime(startDate)
anddate.setTimeInMillis(startTime.getTime())
. 2nd method is overriding the time set in 1st method. You should create 2 separate instances of Calendar.Here is how you can achieve this
Calendar
instances forstartDay
andstartTime
Calendar
object from separateCalendar
objects created in #1 & addday
as per requirementHere is the complete code:
Output:
Note : I suggest using
java.time.*
packages overjava.util.*
. Why? Check this. But this is only available in java 8. (Though, you can use joda time in versions below 8).Edit : Moving Ole V.V. 's comment to answer.
For Java 7, I suggest using
java.time
, the modern Java date and time API, through the backport, ThreeTen Backport.