我有一个日期\时间字符串:
Fri Feb 08 2013 09:47:57 GMT +0530 (IST)
我需要提取日期 (02/08/2013) 和时间 (09:47 am) 部分并将它们存储在两个变量中。
有没有使用 JavaScript 的有效方法?
我写了下面的代码:
var day = elementDate.getDate(); //Date of the month: 2 in our example
var monthNo = elementDate.getMonth(); //Month of the Year: 0-based index, so 1 in our example
var monthDesc = {'0':'January', '1':'February'}; //, "March", "April", "May", "June", "July", "August", "September", "October", "November", "December");
var year = elementDate.getFullYear() //Year: 2013
var hours = elementDate.getHours();
var mins = elementDate.getMinutes();
var lDateValue = (year.toString() + "-" + monthNo.toString() + "-" + day.toString());
document.getElementById("lDate").value = lDateValue;
我的 HTML 中有这个:
<input type="date" name="name" id="lDate" class="custom" value=""/>
<input type="time" name="name" id="lTime" class="custom" value="" />
字段没有更新。 我错过了什么吗?
最佳答案
Date 构造函数非常擅长从字符串创建日期:
使用以下内容:
// This could be any Date String
var str = "Fri Feb 08 2013 09:47:57 GMT +0530 (IST)";
var date = new Date(str);
这将使您能够访问所有日期函数 ( MDN )
例如:
var day = date.getDate(); //Date of the month: 2 in our example
var month = date.getMonth(); //Month of the Year: 0-based index, so 1 in our example
var year = date.getFullYear() //Year: 2013
关于javascript - 从字符串中提取日期和时间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14787271/