Javascript formatting date

I want a date with this format: '%Y-%m-%dT%H:%M:%S+0000'. I wrote a function, but still ask myself if there is a 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 how to do this with less code?

+4
source share
3 answers

This can be done on one line. I made two lines to make it easier. Combine lines 2 and 3.

var d = new Date(); 
date = d.toISOString().toString();
var formattedDate = date.substring(0, date.lastIndexOf(".")) + "+0000";
console.log(formattedDate);
Run codeHide result
+4
source

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>
Run codeHide result
+2
source
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 you want to add it before converting to a string.

+1
source

Source: https://habr.com/ru/post/1657300/


All Articles