简体   繁体   English

无论如何可以使用 date-fns 更改我的日期格式吗?

[英]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.我一直在尝试将存储在数据库中的日期格式更改为分别对应于 2021 年 2 月和 2020 年 12 月的 202102、202012 到 MMM.yy 格式,即 2 月 21 日和 12 月 20 日。 Have tried to use the 'date-fns' library but have not been able to succeed.已尝试使用“date-fns”库但未能成功。 All and any help appreciated, project is built in nodejs.感谢所有和任何帮助,项目是在 nodejs 中构建的。

If using momentjs is an option for you, it's as easy as:如果您可以选择使用momentjs ,那么它很简单:

 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:您可以解析输入字符串,创建一个新的日期 object,然后使用内置的Date.toLocaleString()方法进行格式化以转换日期格式:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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