Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
388 views
in Technique[技术] by (71.8m points)

javascript - Extract date and time from string

I have a dateime string:

Fri Feb 08 2013 09:47:57 GMT +0530 (IST)

I need to extract the date (02/08/2013) and time (09:47 am) parts and store them in two variables.

Is there an efficient way to do it using JavaScript?

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...