使用/不使用Moment.js的日期格式

date formatting with/without Moment.js

本文关键字:js 日期 格式 Moment 使用      更新时间:2023-09-26

我正试图重新格式化我从API获得的日期。在对象中,我有:

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

我想把日期显示为6/13/2013。有人建议我使用moment.js。它有大量的文档,但我对如何使用它有点困惑。有人能帮助或建议一个更简单的方法吗?

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

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

适用:http://jsfiddle.net/K5ub8/2/

有时候你可以这样做

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进行字符串解析。

日期。UTC(年、月、日[、时、分、秒、毫秒]);

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

也许你可以使用split

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("/");

您可以查看此格式时间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
}