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

后端 未结 4 1188
说谎
说谎 2021-01-15 03:33

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 va

相关标签:
4条回答
  • 2021-01-15 04:04

    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()?

    0 讨论(0)
  • 2021-01-15 04:06

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

    0 讨论(0)
  • 2021-01-15 04:22

    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.

    0 讨论(0)
  • 2021-01-15 04:23

    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.

    0 讨论(0)
提交回复
热议问题