9

我正在尝试重新格式化从 API 获取的日期。在我的对象中:

created_at: "2013-06-13T16:29:55.245Z"

我想将日期显示为 2013 年 6 月 13 日。有人建议我使用 moment.js。它有大量的文档,但我对如何使用它有点困惑。有人可以帮忙或建议一种更简单的方法吗?

4

4 回答 4

8

无需修改原始字符串,您可以像这样使用它:

alert(moment("2013-06-13T16:29:55.245Z").format("M/DD/YYYY"));

效果很好:http: //jsfiddle.net/K5ub8/2/

于 2013-06-13T18:00:44.883 回答
4

瞬间你就可以做到这一点

var timeStr = "2013-06-13T16:29:55.245Z",
    newFormat = moment(timeStr).format('M/DD/YYYY');

document.body.textContent = newFormat;
<script src="https://rawgithub.com/timrwood/moment/2.9.0/min/moment.min.js"></script>

输出

6/13/2013 

没有时刻并使用纯字符串操作而不是new Date对象,您可以这样做

var timeStr = "2013-06-13T16:29:55.245Z",
    temp = timeStr.split("T")[0].split("-").reverse(),
    newFormat;

temp[0] = temp.splice(1, 1, temp[0])[0];
newFormat = temp.join("/");
if (newFormat.charAt(0) === "0") {
  newFormat = newFormat.slice(1);
}

document.body.textContent = newFormat;

输出

6/13/2013 

使用Date对象见@Antony 回答答案已删除

或者,如果您需要它与对象更加跨浏览器兼容Date,但仍然是字符串解析。

var timeStr = "2013-06-13T16:29:55.245Z",
    intermediate = timeStr.split("T"),
    newStr = intermediate[0].split("-").join("/") + " " + intermediate[1].split(".")[0] + " GMT",
    newDate = new Date(newStr),
    newFormat = (1 + newDate.getUTCMonth()) + "/" + newDate.getUTCDate() + "/" + newDate.getFullYear();

document.body.textContent = newFormat;

输出

6/13/2013 

最后,您可以将字符串拆分为组件部分并Date.UTC使用这些参数将其输入,而不是让Date字符串解析。

Date.UTC(年,月,日[,时,分,秒,毫秒]);

所以也许你现在可以明白为什么人们建议使用moment.js了,但只要你有知识,那么在没有库的情况下自己做也不会太痛苦。

于 2013-06-13T18:05:14.477 回答
1

也许你可以使用拆分

var tuple = createdAt.split("T");
var date = tuple[0];
var dateTuple = date.split("-");
var day = parseInt(dateTuple[2]);
var month = parseInt(dateTuple[1]);
var year = parseInt(dateTuple[0]);
var newFormatedDate = [ month , day,  year ].join("/");
于 2013-06-13T17:55:29.617 回答
-1

您可以查看此格式时间 API - https://www.mashape.com/parsify/format#!endpoint-Time

我输入了您的日期“2013-06-13T16:29:55.245Z”并得到以下回复 -

{
  "given": "2013-06-13T16:29:55.245Z",
  "time": {
  "daysInMonth": 30,
  "millisecond": 245,
  "second": 55,
  "minute": 29,
  "hour": 16,
  "date": 13,
  "day": 4,
  "week": 24,
  "month": 5,
  "year": 2013,
  "zone": "+0000"
 },
  "formatted": {
  "weekday": "Thursday",
  "month": "June",
  "ago": "2 hours",
  "calendar": "Today at 4:29 PM",
  "generic": "2013-06-13T16:29:55+00:00",
  "time": "4:29 PM",
  "short": "06/13/2013",
  "slim": "6/13/2013",
  "hand": "Jun 13 2013",
  "handTime": "Jun 13 2013 4:29 PM",
  "longhand": "June 13 2013",
  "longhandTime": "June 13 2013 4:29 PM",
  "full": "Thursday, June 13 2013 4:29 PM",
  "fullSlim": "Thu, Jun 13 2013 4:29 PM"
 },
  "array": [
   2013,
   5,
   13,
   16,
   29,
   55,
   245
  ],
 "offset": 1371140995245,
 "unix": 1371140995,
 "utc": "2013-06-13T16:29:55.245Z",
 "valid": true,
 "integer": false,
 "zone": 0
}
于 2013-06-13T18:29:12.717 回答