You can readily parse startTime
if it's in a clearly-defined format, then use setHours
and setMinutes
: Live example | source
var startDateTime;
var parts = /^(\d+):(\d+) (AM|PM)$/.exec(startTime);
if (parts) {
hours = parseInt(parts[1], 10);
minutes = parseInt(parts[2], 10);
if (parts[3] === "PM" && hours !== 12) {
hours += 12;
}
else if (parts[3] === "AM" && hours === 12) {
hours = 0;
}
if (!isNaN(hours) && !isNaN(minutes)) {
startDateTime = new Date(startDate.getTime());
startDateTime.setHours(hours);
startDateTime.setMinutes(minutes);
}
}
...or something along those lines.
Note that key to this is the fact you've said startDate
is a Date
instance. The above assumes we're working within the timezone of the JavaScript environment, not across zones. If you were starting with a date string instead, and that string specified a timezone other than the JavaScript environment's timezone, which you were then converting into a Date
via new Date("Tues Jul....")
, then you'd have to be sure to adjust the resulting Date
to use either the local time of the environment, or UTC; if you adjusted it to be UTC, you'd use setUTCHours
and setUTCSeconds
above instead of setHours
and setSeconds
. Again, this is only an issue if your starting point is a date string, and that string specifies a timezone different from the timezone in which the code above is running.