从字符串中提取日期和时间 [英] Extract date and time from string

查看:539
本文介绍了从字符串中提取日期和时间的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a date\time string:


2013年2月8日星期五09:47:57 GMT +0530(IST)

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

我需要提取日期(2013年2月8日)和时间(上午09:47)部分并将其存储在两个变量中

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

是否有使用JavaScript的有效方法?

Is there an efficient way to do it using 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中有这个:

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?

推荐答案

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

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

使用以下命令:

// This could be any Date String
var str = "Fri Feb 08 2013 09:47:57 GMT +0530 (IST)";
var date = new Date(str);

这将使您可以访问所有Date函数( MDN

This will then give you access to all the Date functions (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

这篇关于从字符串中提取日期和时间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆