Skip to content Skip to sidebar Skip to footer

Creating Date From A Timestring In Javascript

I am new to javascript and am trying to compare two date values ,I am getting two time value strings in the format 06:30:47 AM 01:10:47 PM I need to compare these to find out if th

Solution 1:

I do not think that the standard implementation can parse this. I would do something like this:

functiontoDate(dateString) {
    var timeComponents = dateString.replace(/\s.*$/, '').split(':');

    if (dateString.indexOf("PM") > -1) {
       timeComponents[0] += 12;
    }

    var date = newDate();
    date.setHours(timeComponents[0]);
    date.setMinutes(timeComponents[1]);
    date.setSeconds(timeComponents[2]);

    return date;
}

if (toDate('06:30:47 AM') > toDate('01:10:47 PM')) {
    // ...
}

Solution 2:

JavaScript's specified date/time parsing, what you can rely upon cross-browser, is surprisingly limited. For a long time, there was no single string date format that was mandated in the spec, and as of the recent 5th edition spec, the only mandated format is ISO-8601 (and some subsets). You can't yet rely on browsers having implemented that part of the 5th edition spec.

So you have a couple of choices:

  1. Parse the string yourself and use the Date constructor that takes the individual parts of the date as numbers, e.g. new Date(year, month, day, hour, minute, second, ...). (You need only specify as many of those as you want, so for instance new Date(2010, 9, 14) is September 14th, 2010.)

  2. Use a library like Moment that's already done the work for you. Moment lets you specify the format to parse.

Solution 3:

Use the Date object. Check this: http://www.w3schools.com/jsref/jsref_obj_date.asp

Try putting the two values in Date variables and do this:

if(var1.valueOf() > var2.valueOf())
{
  //Do Something
}

Solution 4:

If your times are always in the format 00:00:00 AM then

var a="06:30:47 AM";
var b="01:10:47 PM";

var at=parseInt(a.substring(0,8).replace(/(^0+|:)/g,""));
var bt=parseInt(b.substring(0,8).replace(/(^0+|:)/g,""));

if (a.charAt(9)=="P") {at=at+120000};
if (b.charAt(9)=="P") {bt=bt+120000};

if (at<bt) {
    // a is smaller
}
else
{
    // a is not smaller
};

..should be cross-browser and time/format safe.

Solution 5:

I tried something like this

var ts1="06:30:47 AM";

var ts2="01:10:47 PM";

var ds=new Date().toDateString();

var d1=new Date(ds+" "+ts1);

var d2=new Date(ds+" "+ts2);

if (!(d2>d1)){

alert("d1 should be less than d2");

}

Is there something wrong with this?

Post a Comment for "Creating Date From A Timestring In Javascript"