更新时间:2023-02-23 18:19:45
Date构造函数非常适用于从字符串创建日期:
使用以下内容:
//这可以是任何Date String
var str =Fri Feb 08 2013 09:47:57 GMT +0530(IST);
var date = new Date(str);
然后,您可以访问所有Date函数( MDN )
例如:
var day = date.getDate(); //本月的日期:我们的例子中的2
var month = date.getMonth(); //年度月份:0个索引,所以在我们的例子中有1个
var year = date.getFullYear()//年份:2013
I have a datetime string generated by system. Ex: Fri Feb 08 2013 09:47:57 GMT +0530 (IST) I need to extract the date (02/08/2013) and Time (09:47 am) and store it in two variables. Is there an efficient way to do it using Javascript?
Edit: I have written the following code.
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;
I have this in my HTML:
<input type="date" name="name" id="lDate" class="custom" value=""/>
<input type="time" name="name" id="lTime" class="custom" value="" />
The fields are not getting updated. Am I missing something?
The Date constructor is very good at creating dates from strings:
Use the following:
// This could be any Date String
var str = "Fri Feb 08 2013 09:47:57 GMT +0530 (IST)";
var date = new Date(str);
This will then give you access to all the Date functions (MDN)
For example:
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