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 ?

4
  • 6
    I recommend using a library like moment.js for this. Commented Oct 10, 2016 at 16:18
  • 2
    I recommend against moment.js in this case. Your solution, while not particularly pretty (Date formatting just isn't nice to code), is going to be a hell of a lot lighter than importing even a lightweight date library. Commented Oct 10, 2016 at 16:21
  • Line 3 is not needed Commented Oct 10, 2016 at 16:22
  • @ViRuSTriNiTy moment.js is 20kb. minified and gzipped Commented Oct 10, 2016 at 16:27

3 Answers 3

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);

Sign up to request clarification or add additional context in comments.

Comments

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>

Comments

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.