Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Formatting Date in javascript [duplicate]

I want date with this format : '%Y-%m-%dT%H:%M:%S+0000'. I wrote a function but still asking myself if there is not better way to do this. This is my function :

 function formatDate() {
     var d = new Date();
     var year = d.getMonth() + 1;
     var day = d.getDate();
     var month = d.getMonth() + 1;
     var hour = d.getHours();
     var min = d.getMinutes();
     var sec = d.getSeconds();
    var date = d.getFullYear() + "-" + (month < 10 ? '0' + month : month) + "-" +
         (day < 10 ? '0' + day : day) +
         "T" + (hour < 10 ? '0' + hour : hour) + ":" + (min < 10 ? '0' + min : min) + ":" + (sec < 10 ? '0' + sec : sec) + "+0000";
     return date;
 }

Any ideal on how to do this with less code ?

like image 703
dmx Avatar asked Oct 10 '16 16:10

dmx


People also ask

How do I format a date in JavaScript?

The JavaScript toDateString() method returns the date portion of a date object in the form of a string using the following format: 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.

Is JavaScript date immutable?

Any function you pass your Date to could potentially mutate your date without you knowing about it, which in turn could introduce nasty and hard-to-find bugs. The new Temporal API is immutable, meaning all methods return a new object instead of mutating the existing one.


2 Answers

It can be done in one line. I made two lines to make it simpler. Combine line 2 and 3.

var d = new Date(); 
date = d.toISOString().toString();
var formattedDate = date.substring(0, date.lastIndexOf(".")) + "+0000";
console.log(formattedDate);
like image 69
Netham Avatar answered Sep 22 '22 02:09

Netham


Use moment.js.

moment().format('YYYY-MM-DDTh:mm:ss+0000')

JSBIN

console.log(moment().format('YYYY-MM-DDTh:mm:ss+0000'))
<script src="https://cdn.jsdelivr.net/momentjs/2.14.1/moment-with-locales.min.js"></script>
like image 28
Vaibhav Mule Avatar answered Sep 21 '22 02:09

Vaibhav Mule