tl;dr
ZonedDateTime.of(
LocalDate.now( ZoneId.of( "America/Montreal" ) )
.with( TemporalAdjusters.next( DayOfWeek.THURSDAY ) ) ,
LocalTime.of( hours , minutes ) ,
ZoneId.of( "America/Montreal" )
).toString()
The ZonedDateTime
class adjusts the time-of-day if invalid for that date in that zone.
java.time
The modern approach uses the java.time classes. Avoid the troublesome old legacy date-time classes seen in the Question.
The LocalDate
class represents a date-only value without time-of-day and without time zone.
A time zone is crucial in determining a date. For any given moment, the date varies around the globe by zone. For example, a few minutes after midnight in Paris France is a new day while still “yesterday” in Montréal Québec.
Specify a proper time zone name in the format of continent/region
, such as America/Montreal
, Africa/Casablanca
, or Pacific/Auckland
. Never use the 3-4 letter abbreviation such as EST
or IST
as they are not true time zones, not standardized, and not even unique(!).
ZoneId z = ZoneId.of( "America/Montreal" );
LocalDate today = LocalDate.now( z );
Determine the DayOfWeek
enum object represented by your UI widget. If tracking by number, that class numbers 1-7 for Monday-Sunday per ISO 8601 standard.
DayOfWeek dow = DayOfWeek.of( 1 ) ; // Monday=1.
Use a TemporalAdjuster
found in TemporalAdjusters
to determine the next date with that same day-of-week.
LocalDate ld = today.with( TemporalAdjusters.next( dow ) ) ;
Instantiate a LocalTime
from your hours and minutes numbers.
LocalTime lt = LocalTime.of( hours , minutes );
Combine to determine an actual moment in the timeline.
ZonedDateTime zdt = ZonedDateTime.of( ld , lt , z ) ;
Your particular time-of-day may not be valid for that date in that zone because of anomalies such as Daylight Saving Time (DST). The ZonedDateTime
class adjusts as needed. Be sure to read the class doc to understand its policies in making that adjustment.
You can serialize that object to text using the standard ISO 8601 format, extended by this class to append the name of the time zone in square brackets.
String output = zdt.toString() ;
Reconstitute the object by parsing such strings.
ZonedDateTime zdt = ZonedDateTime.parse( input ) ;
About java.time
The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date
, Calendar
, & SimpleDateFormat
.
The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
Where to obtain the java.time classes?