如何将 JavaScript 中的“2016-03-10 16:00:00.0”转换为 2016 年 3 月 10 日?

How do i convert "2016-03-10 16:00:00.0" to March 10,2016 in JavaScript?

我得到一个日期字符串,我需要将其转换为 javascript 中的其他日期格式。

https://msdn.microsoft.com/en-us/library/ff743760(v=vs.94).aspx

https://msdn.microsoft.com/en-us/library/az4se3k1(v=vs.110).aspx

这两个链接应该能让您朝着正确的方向开始。

你可以做类似的事情 var myDate = new Date("2016-03-10 16:00:00.0"); myDate.toString("m")

打印出来: "Thu Mar 10 2016 16:00:00 GMT-0800 (Pacific Standard Time)"

然后你就可以把它解析出来,得到你想要的部分。或者您可以查看上面链接中的其他 return toString 格式。

所有浏览器

使用您正在使用的源格式设置日期格式的最可靠方法是应用以下步骤:

  1. 使用 .replace(/ /g,'T') 将您的日期转换为 ISO 8601
  2. 将其用作 new Date()
  3. 的输入
  4. .getDate().getMonth().getFullYear()分别得到日、月、年
  5. 根据您的目标格式将片段粘贴在一起

下面的 format 函数向您展示了结合这四个步骤的最佳方式:

var date = '2016-03-10 16:00:00.0';

function format(input) {
    var date = new Date(input.replace(/ /g,'T'));
    return [
        "January", "February", "March", "April", "May", "June", "July",
        "August", "September", "October", "November", "December"
    ][date.getMonth()] + ' ' + date.getDate() + ', ' + date.getFullYear();
}

document.body.innerHTML = format(date); // OUTPUT : "March 10, 2016"

(另见 this Fiddle)。

仅限现代浏览器

您也可以使用内置的 .toLocaleDateString 方法为您进行格式化。您只需要传递正确的语言环境和选项以匹配正确的格式,不幸的是,只有现代浏览器支持 (*) :

var date = '2016-03-10 16:00:00.0';

function format(input) {
    var dateFormat = { year: 'numeric', month: 'long', day: 'numeric' };
    return new Date(input.replace(/ /g,'T')).toLocaleDateString('en-US', dateFormat);
}

document.body.innerHTML = format(date); // OUTPUT : "March 10, 2016"

(另见 this Fiddle)。


(*) According to the MDN, "Modern browsers" means Chrome 24+, Firefox 29+, IE11, Edge12+, Opera 15+ & Safari nightly build