Convert time string, say "12:05 PM" to datetime using Date.Parse in javascript

I want to convert the time string say '12: 05 PM 'to 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 go to 1:00 PM, 1:05 PM, 1:10 PM, 12:00 AM, ..., 12:00 PM it works fine
returning me the date with the included time.

This is the line of code causing the problem:

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

And StartTime is a text box.

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

+2
source share
4 answers

If you use date.js, try (for example, here is a test case )

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

This should also be selected if you loaded the library correctly.

+3
source

It works great here:

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

This may be a problem loading the library, but you are saying that it has been working for a while and not others. Have you tried to output the value of the text field to the console before submitting it to Date.parse() ?

+2
source

there is a good utility for dates named date.js.

+1
source

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 your answer to another question that you use date.js. If you really use it, your code is correct, then the problem should be that you are not loading the library properly, and use your own Date object.

+1
source

Source: https://habr.com/ru/post/1247970/


All Articles