Javascript 从字符串中提取日期和时间

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14787271/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 17:54:59  来源:igfitidea点击:

Extract date and time from string

javascriptdatetime

提问by SuperFunMan

I have a date\time string:

我有一个日期\时间字符串:

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

2013 年 2 月 8 日星期五 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.

我需要提取日期 (02/08/2013) 和时间 (09:47 am) 部分并将它们存储在两个变量中。

Is there an efficient way to do it using JavaScript?

有没有一种使用 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:

我的 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?

这些字段没有得到更新。我错过了什么吗?

回答by phenomnomnominal

The Date constructor is very good at creating dates from strings:

Date 构造函数非常擅长从字符串创建日期:

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)

这将使您可以访问所有日期功能(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