簡體   English   中英

無論如何可以使用 date-fns 更改我的日期格式嗎?

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

我一直在嘗試將存儲在數據庫中的日期格式更改為分別對應於 2021 年 2 月和 2020 年 12 月的 202102、202012 到 MMM.yy 格式,即 2 月 21 日和 12 月 20 日。 已嘗試使用“date-fns”庫但未能成功。 感謝所有和任何幫助,項目是在 nodejs 中構建的。

如果您可以選擇使用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>

您可以解析輸入字符串,創建一個新的日期 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