Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

date formatting with/without Moment.js

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?

like image 427
Anthony Avatar asked Jun 13 '13 17:06

Anthony


People also ask

What can I use instead of moment in JavaScript?

And today, the most popular alternative to Moment. js is Day. js which surpassed date-fns on GitHub by stars (46,2k Day. js stars vs 37,7k date-fns stars).

How do I format a date in JavaScript?

The toDateString() Method in JavaScript First three letters of the week day name. First three letters of the month name. Two digit day of the month, padded on the left a zero if necessary. Four digit year (at least), padded on the left with zeros if necessary.


2 Answers

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/

like image 93
Antoine Avatar answered Oct 01 '22 13:10

Antoine


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.

like image 25
Xotic750 Avatar answered Oct 01 '22 13:10

Xotic750