Please see the below code;
var d = new Date();
var s = "01.00 AM";
d.setTime(s);
I know this code is wrong. Please give me the correct way to set the time. I have 12 hour time in string format in my hand.
The time will vary. Cannot know what will be the time earlier. Also it is 12 hour time. So it will be AM or PM
Use the Date() constructor to convert a string to a Date object, e.g. const date = new Date('2022-09-24') . The Date() constructor takes a valid date string as a parameter and returns a Date object. Copied! We used the Date() constructor to convert a string to a Date object.
Using strptime() , date and time in string format can be converted to datetime type. The first parameter is the string and the second is the date time format specifier. One advantage of converting to date format is one can select the month or date or time individually.
You can parse the time with a regex, and set the hours and minutes accordingly:
http://jsfiddle.net/54VkC/1/
var d = new Date(),
s = "01.25 PM",
parts = s.match(/(\d+)\.(\d+) (\w+)/),
hours = /am/i.test(parts[3]) ? parseInt(parts[1], 10) : parseInt(parts[1], 10) + 12,
minutes = parseInt(parts[2], 10);
d.setHours(hours);
d.setMinutes(minutes);
alert(d);
Edit 1: As jaisonDavis pointed out, the original code will not work for AM or PM for 12.XX, which was an oversight since I never use 12-hour format myself, thinking it started at 00.00 which was wrong.
The corrected code which handles these cases can be seen here:
http://jsfiddle.net/54VkC/93/
var test, parts, hours, minutes, date,
d = (new Date()).getTime(),
tests = ['01.25 PM', '11.35 PM', '12.45 PM', '01.25 AM', '11.35 AM', '12.45 AM'],
i = tests.length,
timeReg = /(\d+)\.(\d+) (\w+)/;
for(; i-- > 0;) {
test = tests[i];
parts = test.match(timeReg);
hours = /am/i.test(parts[3]) ?
function(am) {return am < 12 ? am : 0}(parseInt(parts[1], 10)) :
function(pm) {return pm < 12 ? pm + 12 : 12}(parseInt(parts[1], 10));
minutes = parseInt(parts[2], 10);
date = new Date(d);
date.setHours(hours);
date.setMinutes(minutes);
console.log(test + ' => ' + date);
}
I'm late to the party, but I thought I'd share a funtion that doesn't use regex:
function setDateTime(date, time) {
var index = time.indexOf("."); // replace with ":" for differently displayed time.
var index2 = time.indexOf(" ");
var hours = time.substring(0, index);
var minutes = time.substring(index + 1, index2);
var mer = time.substring(index2 + 1, time.length);
if (mer == "PM"){
hours = hours + 12;
}
date.setHours(hours);
date.setMinutes(minutes);
date.setSeconds("00");
return date;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With