在javascript中将日期从'2011年6月9日00:00:00 GMT + 0530(印度标准时间)'转换为'YYYY-MM-DD' [英] Convert date from 'Thu Jun 09 2011 00:00:00 GMT+0530 (India Standard Time)' to 'YYYY-MM-DD' in javascript

查看:72
本文介绍了在javascript中将日期从'2011年6月9日00:00:00 GMT + 0530(印度标准时间)'转换为'YYYY-MM-DD'的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何将时间格式从2011年6月9日00:00:00 GMT + 0530(印度标准时间)转换为YYYY-MM-DD。

How can I convert the time from the format "Thu Jun 09 2011 00:00:00 GMT+0530 (India Standard Time)" to YYYY-MM-DD.

当我尝试提醒()日期时,这将显示日期,如下面的
- 2011年6月9日星期四00:00:00 GMT + 0530(印度标准时间)

When I try to alert() the date then this will show the date like the following - Thu Jun 09 2011 00:00:00 GMT+0530 (India Standard Time)

但我需要时间为YYYY-MM-DD格式。

But I need the time in YYYY-MM-DD format.

是否有任何内置函数可以转换?

Are there any built function to convert?

推荐答案

您可以使用 Date 构造函数解析日期,然后吐出各个时间组件:

You can parse the date using the Date constructor, then spit out the individual time components:

function convert(str) {
    var date = new Date(str),
        mnth = ("0" + (date.getMonth()+1)).slice(-2),
        day  = ("0" + date.getDate()).slice(-2);
    return [ date.getFullYear(), mnth, day ].join("-");
}

convert("Thu Jun 09 2011 00:00:00 GMT+0530 (India Standard Time)");
//-> "2011-06-08"

从结果中可以看出,这将解析日期进入当地时区。如果您想根据原始时区保留日期,最简单的方法是拆分字符串并提取您需要的部分:

As you can see from the result though, this will parse the date into the local time zone. If you want to keep the date based on the original time zone, the easiest approach is to split the string and extract the parts you need:

function convert(str) {
    var mnths = { 
        Jan:"01", Feb:"02", Mar:"03", Apr:"04", May:"05", Jun:"06",
        Jul:"07", Aug:"08", Sep:"09", Oct:"10", Nov:"11", Dec:"12"
    },
    date = str.split(" ");

    return [ date[3], mnths[date[1]], date[2] ].join("-");
}

convert("Thu Jun 09 2011 00:00:00 GMT+0530 (India Standard Time)");
//-> "2011-06-09"

这篇关于在javascript中将日期从'2011年6月9日00:00:00 GMT + 0530(印度标准时间)'转换为'YYYY-MM-DD'的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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