23

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

5 Answers 5

29

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);
}

Sign up to request clarification or add additional context in comments.

3 Comments

If the time is between 12.00 PM and 12.59 PM it still adds 12 hours to the time, which makes the time 12.** AM
@jaisonDavis You are right, thank you for catching it, I don't really use 12-hour format myself. I have made an addition to the original answer, which handles these cases. And I will be sure to remember 12.XX when I work with 12-hour format in the future :-)
this is exactly what I was looking for.. thank you!!
15

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;
}

Comments

5

Using moment.js will be the easy solution.

const fullDate = new Date();
// fullDate = Tue Dec 12 2017 11:18:30 GMT+0530 (IST) {}
const time = '01.00 AM';
const d = moment(fullDate).format('L'); // d = "12/12/2017"
const date = moment(d +' '+ time).format();
// date = "2017-12-12T01:00:00+05:30"

If you want convert moment date to js date

const jsDate = moment(date).toDate();

3 Comments

Why will it be 'best'?
I highly doubt this is the 'best' solution, pushing the user to bring in a huge third-party library for such a simple functionality should be expressed with great caution.
well I change my word from 'best' to 'easy'
1
function getCurrentDate() {
    var lDate = new Date();
    var lDay = lDate.getDate();
    var lMonth = lDate.getMonth() + 1;
    var lYear = lDate.getFullYear();

    if (lDay < 10) {
        lDay = '0' + lDay
    }

    if (lMonth < 10) {
        lMonth = '0' + lMonth
    }
    mCurrentDate = lYear + "-" + lMonth + "-" + lDay + "T00:00:00+05:30";
}

Comments

1

I added a few things as an improvement to the accepted answer by @thebreiflabb to suit my use case and thought i'd share.

if the regex is changed to timeReg = /(\d+)[\.|:](\d+)\s?(\w+)/;, it'll handle a few other common cases.

namely:

  • using a colon instead of decimal point between hours and minutes
  • allowing am/pm to immediately follow the time with no space

also, setting the seconds to 0 (since that was my main use case)

the resulting code would be:

var test, parts, hours, minutes, date,
    d = (new Date()).getTime(),
    tests = ['01.25 PM', '01:25pm', '1:25 PM', '11.35 PM', '12.45 PM', '01.25 AM', '11.35 AM', '12.45 AM'],
    i = tests.length,
    timeReg = /(\d+)[\.|:](\d+)\s?(\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);
    date.setSeconds(0);

    console.log(test + ' => ' + date);
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.