Convert a time string say '12:05 PM' into a datetime using Date.Parse in Javascript

19,261

Solution 1

If you're using date.js then try (as per test case here)

Date.parseExact("12:05 PM", "hh:mm tt");

This should also pick up if you've loaded the library correctly.

Solution 2

It works fine here:

http://jsfiddle.net/vuURb/396/

It's possible that it is a library loading issue, but you claim it works on some times and not others. Have you tried outputting the value of the text box to the console before feeding it to Date.parse()?

Solution 3

there's a good utility for dates named date.js.

Solution 4

Based on this answer you can do this:

var startTime = new Date();
var time = $("#<%= StartTime.ClientID %>").val().match(/(\d+)(?::(\d\d))?\s*(p?)/);
startTime.setHours(parseInt(time[1]) + (time[3] ? 12 : 0) );
startTime.setMinutes( parseInt(time[2]) || 0 );

I just read on your reply to the other question that you are using date.js. If you really are using it, your code is correct, then the problem should be that you are not loading the library properly, and you are using the native Date object.

Share:
19,261
Ruruboy
Author by

Ruruboy

Founder of a start up Software Consulting company providing consulting services to IT companies in North America. I like writing code in MS.NET, C#, SQL Server,etc as its embedded in my soul and is a passionate phase of my existence in this world. Software Development is the essence of existence. One does not need an interview to validate his knowledge but a computer to test his skill level. Computing is the abstract on which an entity can be evaluated.

Updated on June 05, 2022

Comments

  • Ruruboy
    Ruruboy almost 2 years

    I want to convert a time string say '12:05 PM' into a datetime using Date.Parse in Javascript. When I pass in a value of say 12:05 PM or 12:10 PM or ... or 12:55 PM the value returned by startTime below is null, i.e. startTime = null

    But when I pass in values of 1:00 PM, 1:05 PM, 1:10 PM, 12:00 AM,...,12:00 PM it works fine
    returning me a Date with the time included.

    This is the code line causing an issue:

    var startTime = Date.parse($("#<%= StartTime.ClientID %>").val());  //code causing the issue
        
    

    And StartTime is a textbox.

    I am writing the above code in client/html in an ASP.NET application on the web form.