简体   繁体   中英

How to set time with AM PM in Javascript Date Object

Say that I have DateTime in this format Fri Feb 02 2018 00:00:00 GMT+0530 (IST)

And from the time picker plugin getting the time 1:10am or 2:30pm in this format.

I am not sure how to calculate and combine/add them both to produce this result:
Fri Feb 02 2018 01:10:00 GMT+0530 (IST) or Fri Feb 02 2018 14:30:00 GMT+0530 (IST)

I wish if there was something to do as simple as this:
new Date(dateString).setHours(1:10am)

Here is a simple function to do what your after.

It basically splits the time using a regex, and then calls setHours & setMins, adding 12 hours if pm is selected.

The example below takes the current datetime, and sets 1:10am & 2:40pm..

 function setHours(dt, h) { var s = /(\\d+):(\\d+)(.+)/.exec(h); dt.setHours(s[3] === "pm" ? 12 + parseInt(s[1], 10) : parseInt(s[1], 10)); dt.setMinutes(parseInt(s[2],10)); } var d = new Date(); console.log(d); setHours(d, "1:10am"); console.log(d); setHours(d, "2:40pm"); console.log(d); 

Seems like you need to parse it on your own:

function parseDaytime(time) {
  let [hours, minutes] = time.substr(0, time.length  -2).split(":").map(Number);
  if (time.includes("pm") && hours !== 12) hours += 12;
  return 1000/*ms*/ * 60/*s*/ * (hours * 60 + minutes);
}

To add it to a date:

new Date(
  +new Date("Fri Feb 02 2018 00:00:00 GMT+0530")
  +parseDaytime("1:20pm")
);

You can parse the time string into hours & minutes, adjust the hours according to am/pm & set it to the date object then:

var dateString = 'Fri Feb 02 2018 00:00:00 GMT+0530 (IST)';
var hoursString = '2:30pm';
var parts = hoursString.replace(/am|pm/, '').split(':')
var hours = parseInt(parts[0]) + (hoursString.indexOf('pm') !== -1 ? 12 : 0);
var minutes = parts[1];
var date = new Date(dateString);
date.setUTCHours(hours, minutes);
console.log(date); // in your local time
console.log(date.toUTCString()); // in UTC (i.e. without timezone offset)

(Note setHours / setUTCHours mutates date object but returns unix timestamp of the updated datetime.)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM