10

I am trying to reformat a date that I am getting from an API. In the object I have:

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

I would like to display the date as 6/13/2013. Someone suggested I use moment.js. It has tons of documentation but i'm a bit confused on how to use it. can someone please help or suggest an easier way to do this?

Antony
  • 14,900
  • 10
  • 46
  • 74
Anthony
  • 2,330
  • 8
  • 44
  • 64

4 Answers4

8

No need to modify the original string, you can just use it like this:

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

Works well: http://jsfiddle.net/K5ub8/2/

Antoine
  • 2,785
  • 1
  • 16
  • 23
4

In moments you can just do this

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>

Output

6/13/2013 

Without moments and using pure string manipulation rather than a new Date object, you could do

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;

Output

6/13/2013 

By using the Date object see @Antony answer. Answer removed

Or if you need it to be more cross-browser compatible with the Date object but still string parsing.

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;

Output

6/13/2013 

Finally, you can split the string into component parts and feed it into Date.UTC using these arguments, rather than let Date do the string parsing.

Date.UTC(year, month, day [, hour, minute, second, millisecond]);

So perhaps you can now see why people suggest using moments.js, but so long as you have the knowledge then it is not too painful to do it yourself without a library.

Community
  • 1
  • 1
Xotic750
  • 22,914
  • 8
  • 57
  • 79
  • I love your `moment(timeStr).format('M/DD/YYYY');` approach, but make sure you mention that if you use, for example, `0000-01-01T00:00:00.0Z`, and are not in the GMT timezone or east of it, up until the international dateline, it will translate that as December 31st, instead of January 1st. This applies to those of us in the U.S., for example: for EST, we would need to put `05:00:00.0Z`. – vapcguy Mar 04 '15 at 02:27
  • @vapcguy Should be fixed now, added the missing "GMT" when parsing and pointed to Date.UTC when using parts. – Xotic750 Mar 04 '15 at 21:27
  • I was referring more to how everyone, except those in GMT, would need to make sure they accounted for timezones when using the examples to get it into their own local time. It's easy to get it into GMT/UTC, I was talking more about how to get it out of it, and my point was more with hard-coding a date. `Date.UTC()` will give you the milliseconds since midnight, 1/1/1970, UTC time, but you still need to use `new Date()`, like `new Date(Date.UTC(96, 11, 1, 0, 0, 0));` to get a date/time that is good for your local area. And using those numbers will give me Nov 30 at 7 PM, not Dec 1st at 12 AM. – vapcguy Mar 05 '15 at 03:43
  • My point was if I intended to hard-code a date, say, into a Kendo datepicker using a KnockOut viewmodel, I would need to specify it as 5 hours later than I might have otherwise, since I am GMT-5, in EST. So instead of thinking I could do `var dateString = 0000-01-01T00:00:00.0Z`, I had to do `var dateString = 0000-01-01T05:00:00.0Z`. My string looked like: `this.MyDate = ko.observable(new Date(moment(dateString).format('MM/DD/YYYY'));` (Of course, I later found out the earliest supported Kendo datepicker date, unless it's just our configs, is 1/1/1900... but that's another story.) – vapcguy Mar 05 '15 at 03:51
  • Of course if you parse the date as UTC and read it back as UTC and you want it hardcoded for another timezone then you will have to make changes to the above code, i.e. add the appropriate amount of hours, with moments you can specify the timezone. But as it stands, the code above should give you the same result regardless of your local settings, i.e. UTC – Xotic750 Mar 05 '15 at 07:59
  • You might not realize this, but using "new Date()" on a UTC date will put it into local time. I was not parsing into UTC. The problem is how it will translate. I wasn't sure why you did newStr as GMT, then new Date() on it (local time), then newFormat using UTC again? – vapcguy Mar 06 '15 at 17:58
  • 1
    And these examples. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/parse#Examples – Xotic750 Mar 06 '15 at 21:07
  • I've created a fork of your fiddle - it may help to demonstrate what I'm saying: http://jsfiddle.net/navyjax2/zLp1kjkw – vapcguy Mar 07 '15 at 01:28
  • From your link: **Differences in assumed time zone** Given a date string of "March 7, 2014", `parse()` assumes a local time zone, but given an ISO format such as "2014-03-07" it will assume a time zone of UTC. Therefore Date objects produced using those strings will represent different moments in time unless the system is set with a local time zone of UTC. This means that two date strings that appear equivalent may result in two different values depending on the format of the string that is being converted (this behavior is changed in ECMAScript ed 6 so that both will be treated as local). – vapcguy Mar 07 '15 at 01:42
  • 1
    Yes, that is why I gave a link to a very old table http://dygraphs.com/date-formats.html that shows some of these differences. It is well know that relying on `Date.parse` is a bad idea and that you are better off performing the parse yourself (for the string that you are using) and then feeding the parts either into `Date` or `Date.UTC`, depending on your requirements. That's why is suggested the string manipulation first. Here is a further example http://stackoverflow.com/questions/27720916/converting-string-into-date-format-in-js/27721275#27721275 – Xotic750 Mar 07 '15 at 09:02
1

maybe you can use 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("/");
Edorka
  • 1,781
  • 12
  • 24
  • Better, it now gives `06/13/2013` but the OP wanted `6/13/2013`: http://jsfiddle.net/Xotic750/mRPcP/ – Xotic750 Jun 13 '13 at 20:28
  • Lol. sorry I didn't noticed the 0 at month – Edorka Jun 13 '13 at 20:35
  • That now works, though the OP didn't specify whether they wanted a leading zero in the day or not, only on month, and year shouldn't have any (most likely), +1 – Xotic750 Jun 13 '13 at 20:39
-1

You can check out this Format Time API - https://www.mashape.com/parsify/format#!endpoint-Time

I typed in your date "2013-06-13T16:29:55.245Z" and got the following response -

{
  "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
}
Chris Ismael
  • 612
  • 5
  • 13
  • 14