6

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 ?

dmx
  • 1,482
  • 1
  • 19
  • 33

3 Answers3

5

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);
Netham
  • 1,182
  • 6
  • 15
1

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>
Community
  • 1
  • 1
Vaibhav Mule
  • 4,447
  • 3
  • 31
  • 51
1
var d = new Date();
var dateString = d.getUTCFullYear() +"-"+ (d.getUTCMonth()+1) +"-"+ d.getUTCDate() + " " + d.getUTCHours() + ":" + d.getUTCMinutes() + ":" + d.getUTCSeconds()+"+0000";

getUTCMonth returns 0 - 11, so want to add one before you convert to string.

Chandana Kumara
  • 2,129
  • 1
  • 17
  • 23