将 Javascript 字符串转换为日期时间
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14614655/
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
Converting Javascript String to Datetime
提问by APW
I have a text box that is populated from a datepicker in Javascript. The date is stored as 30-Jan-2013
. I want to convert this to a date so I can use it in other calculations.
我有一个文本框,它是从 Javascript 中的日期选择器填充的。日期存储为30-Jan-2013
. 我想将其转换为日期,以便我可以在其他计算中使用它。
I have tried
我努力了
var date1 = new Date(document.getElementById('textbox').value)
but this returns Nan
但这会返回 Nan
if I drop the new Date
part e.g.
如果我放下new Date
零件,例如
var date1 = (document.getElementById('textbox').value
I get the date 30-Jan-2013
I just don't seem to be able to convert this?
我得到了30-Jan-2013
我似乎无法转换的日期?
采纳答案by Kelsey
Looks like Date.parse
is not going to work because the format the datepicker is returning.
看起来Date.parse
不会工作,因为日期选择器返回的格式。
You might want to look at the following thread for parsing solutions or change your format that the datepicker outputs to one of the supported formats.
您可能希望查看以下线程以解析解决方案或将日期选择器输出的格式更改为支持的格式之一。
How can I convert string to datetime with format specification in JavaScript?
如何使用 JavaScript 中的格式规范将字符串转换为日期时间?
http://blog.dygraphs.com/2012/03/javascript-and-dates-what-mess.html
http://blog.dygraphs.com/2012/03/javascript-and-dates-what-mess.html
Useful parse info:
有用的解析信息:
http://msdn.microsoft.com/en-us/library/ie/ff743760(v=vs.94).aspx
http://msdn.microsoft.com/en-us/library/ie/ff743760(v=vs.94).aspx
回答by Vadim Ivanov
I'd like to recommend you a simple, easy to use and fast library [moment.js][1]
我想向您推荐一个简单易用且快速的库 [moment.js][1]
moment("30-Jan-2013").format('MMMM Do YYYY, h:mm:ss a');
will return "January 30th 2013, 12:00:00 am"
将返回“2013 年 1 月 30 日,12:00:00 am”
回答by Joy Acharya
Hope this will work for your problem
希望这对您的问题有用
var date= document.getElementById('textbox').value.split("-");;
var date1 = new Date(date[2] + " " + date[1] + " " + date[0]);
date1 .toLocaleDateString("en-GB");