Reputation: 26451
I have two date variable separately like following
startDate
is a Date
instance with the value Tue Jul 17 2012 00:00:00 GMT+0530 (IST)
startTime
is a String
with the value "11:30 AM"
Now what I need is join of both above date & time, as a Date
.
startDateTime
= Tue Jul 17 2012 11:30:00 GMT+0530 (IST)
I tried
new Date(startDate + " " + startDate)
but outputting invalid date
.
Also tried the way shown on this post. But still not working.
Upvotes: 2
Views: 5111
Reputation: 1075735
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.
Upvotes: 4
Reputation: 665536
Try
new Date(startDate.toDateString() + " " + startTime)
This combines the date string from your Date
object with the time string, and should give you a valid date. Note that this ignores the timezone you initially worked with, you might need to add " GMT+0530"
again.
However, because your date string is already timezone-biased (Jul 16 2012, 20:30:00 UTC) it might be better to add them together, i.e. like new Date(+startDate + milliseconds)
:
var startDate = new Date("Tue Jul 17 2012 00:00:00 GMT+0530");
var startTime = "11:30 AM";
return new Date(+startDate + +new Date("1 1 1970 "+startTime))
Upvotes: 0
Reputation: 6479
You can do This:
var theDate = new Date("Tue Jul 17 2012 00:00:00 GMT+0530 (IST)");
var theTime = "11:30 AM";
var hours = theTime .substr(0,2);
var minutes = theTime .substr(3,2);
var amOrPm = theTime .substr(6,2);
if (hours < 12 && "PM" == amOrPm) {
hours = +hours + 12;
}
theDate.setHours(hours);
theDate.setMinutes(minutes);
Upvotes: 2