使用 javascript 中的 Date.Parse 将时间字符串说“12:05 PM”转换为日期时间

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9729484/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 07:38:25  来源:igfitidea点击:

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

javascriptjqueryasp.netjavascript-events

提问by Ruruboy

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

我想使用 javascript 中的 Date.Parse 将时间字符串“12:05 PM”转换为日期时间。当我传入 12:05 PM 或 12:10 PM 或 ... 或 12:55 PM 的值时,下面的 startTime 返回的值为空,即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.

但是,当我传入 1:00 PM、1:05 PM、1:10 PM、12:00 AM、...、12:00 PM 的值时,它可以很好地
返回一个包含时间的日期。

This is the code line causing an issue:

这是导致问题的代码行:

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

And StartTime is a textbox.

而 StartTime 是一个文本框。

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

我正在 Web 表单上的 ASP.NET 应用程序中的 client/html 中编写上述代码。

回答by jhsowter

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

如果您使用的是 date.js,请尝试(根据此处的测试用例

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

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

如果您正确加载了库,这也应该会出现。

回答by Jeff B

It works fine here:

它在这里工作正常:

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

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

这可能是库加载问题,但您声称它在某些时候有效,而在其他时候无效。您是否尝试在将文本框的值输入到控制台之前将其输出到控制台Date.parse()

回答by Taha Paksu

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

对于名为date.js 的日期,有一个很好的实用程序。

回答by davoclavo

Based on this answeryou 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.

我刚刚阅读了您对另一个问题的回复,即您正在使用date.js。如果您真的在使用它,您的代码是正确的,那么问题应该是您没有正确加载库,并且您使用的是本机 Date 对象。