-1

I have a date format like this "2016-07-14T10:52:36.000Z" and I want to convert it to yyyymmddhis format.

The reason is that in my project I have files stored in AWS S3 where link is generated via the upload time.

I have tried using moment.js moment("2016-07-14T10:52:36.000Z").format('yyyymmddhis');

Can any body help?

3 Answers3

0

The format string is wrong.

Change

.format('yyyymmddhis')

To

.format('YYYYMMDDHms')

Or

.format('YYYYMMDDHHmmss')  // with "0" padding for hours/minutes/seconds

var output = moment("2016-07-14T10:52:36.000Z").format('YYYYMMDDHHmmss');
console.log(output);
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.24.0/moment.js"></script>
Andreas
  • 21,535
  • 7
  • 47
  • 56
0

May be if you don't want to use any third party library then you can create javascript date prototype

Date.prototype.customFormat = function(){
var currentDate = new Date(this);
var currentMonth = currentDate.getMonth() >= 9 ? currentDate.getMonth() + 1 : "0" + (currentDate.getMonth() +1);
return currentDate.getFullYear().toString()+currentMonth+currentDate.getDate().toString()+currentDate.getHours().toString()
+currentDate.getMinutes().toString()+currentDate.getSeconds().toString();
};

Use:

new Date("2016-07-14T10:52:36.000Z").customFormatt()

Output:

20160714162236
Mox Shah
  • 2,967
  • 2
  • 26
  • 42
-1

There is no need to convert to a Date or use a large library. Just modify the string:

let s = "2016-07-14T10:52:36.000Z"

console.log(s.replace(/\D/g,'').substr(0,14))
RobG
  • 142,382
  • 31
  • 172
  • 209
  • This won`t work as timezone is also embed in the datetime string, hence your answer will always return incorrect value. – Prabhjot Singh Kainth Dec 26 '19 at 07:09
  • @PrabhjotSinghKainth—it works as required and provides a result identical to the accepted answer. The OP specified a format without a timezone. It would be trivial to preserve the timezone if necessary. – RobG Dec 26 '19 at 11:39
  • Kindly check this https://stackoverflow.com/questions/8405087/what-is-this-date-format-2011-08-12t201746-384z – Prabhjot Singh Kainth Dec 26 '19 at 12:06
  • @PrabhjotSinghKainth—I don't see how that question is relevant. – RobG Dec 27 '19 at 03:25