简体   繁体   中英

How to convert ISO Date format to yyyymmddhsi format?

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?

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>

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM