简体   繁体   中英

Is there anyway to change my date format using date-fns?

I have been trying to change my date format, stored in the database as 202102, 202012 corresponding to 2021 Feb and 2020 December respectively to the MMM.yy format that is Feb-21 and Dec-20 respectively. Have tried to use the 'date-fns' library but have not been able to succeed. All and any help appreciated, project is built in nodejs.

If using momentjs is an option for you, it's as easy as:

 const result = moment("202102", "YYYYMM").format("MMM-YY"); console.log(result);
 <script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.1/moment.min.js"></script>

You could parse the input strings, create a new Date object, then format using the built-in Date.toLocaleString() method to convert the date format:

 const inputs = ["200501", "202012", "202102", "202107", "202210"]; function convertDateFormat(input) { const date = new Date(+input.substr(0,4), +input.substr(4,2) - 1, 1); return date.toLocaleString('en', { year: '2-digit', month: 'short' } ).replace(' ','-'); } inputs.forEach(input => console.log(`Input: ${input}, Output: ${convertDateFormat(input)}`));

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