如何在 JavaScript 中解析日期时间
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16991664/
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
How to parse date time in JavaScript
提问by Watt
I have Date in this format mm/dd/yy
example: 04/11/13
and time in the format HH:MM:SS
example: 17:02:30
我有这个格式mm/dd/yy
示例中的日期:04/11/13
和格式示例中的时间HH:MM:SS
:17:02:30
I have to parse above two values and put in a variable dateTime
with following format
我必须解析以上两个值并放入一个dateTime
具有以下格式的变量
YYYY-MM-DDTHH:MM:SSS
2013-04-11T17:02:30.000
What is best way to do it in AngularJS or in Javascript. I also need to verify the user input and make sure it is a valid mm/dd/yy
date and a valid HH:MM:SS
time
在 AngularJS 或 Javascript 中执行此操作的最佳方法是什么。我还需要验证用户输入并确保它是有效mm/dd/yy
日期和有效HH:MM:SS
时间
I know there are tons of duplicate/similar questions but I couldn't find one which answers above, please let me know if you found one.
我知道有很多重复/类似的问题,但我找不到上面的答案,如果你找到了,请告诉我。
回答by Oliver
You don't need an external library to do this. See this doc linkfor the forms of date that JavaScript can process normally.
您不需要外部库来执行此操作。有关JavaScript 可以正常处理的日期形式,请参阅此文档链接。
For a specific solution to your question:
对于您的问题的具体解决方案:
var date = new Date("04/11/13" + " " + "17:02:30");
date.toISOString();
>> "2013-04-11T21:02:30.000Z"
See this MDN pagefor more info on the Date object.
有关Date 对象的更多信息,请参阅此 MDN 页面。
回答by frosty
The best way to do this in AngularJS is with a filter. You bind to the dateTime, and then filter it with the date filter.
在 AngularJS 中执行此操作的最佳方法是使用过滤器。您绑定到日期时间,然后使用日期过滤器对其进行过滤。
<span>{{myDate | date:yyyy-MM-ddThh:mm:sss}}</span>
Or in your controller you say:
或者在你的控制器中你说:
$filter('date')(date[, format])
Here is more info: http://docs.angularjs.org/api/ng.filter:date
这是更多信息:http: //docs.angularjs.org/api/ng.filter: date