如何在矩/日期中格式化至mm/dd/yyyy?

发布于 2025-02-13 21:24:22 字数 489 浏览 2 评论 0原文

在这里,我将最后一个更新的数据作为这样的API响应,

let data = {
          "year": 2021,
          "monthValue": 11,
          "dayOfMonth": 9
         }

我必须将上述对象掩盖此格式mm/dd/yyyy

可以使用字符串插值(例如$ {data.data.dayofmonth}/$ {data.monthvalue}/$ {data.year},可以使用字符串插值转换上述数据工作完成。

例如,在上面的字符串插值方法中,无法在dayofmonthmonthvalue时添加0单位数字。

我们可以使用MONSdate-fns来实现这一目标吗?

Here I am receiving the last updated data as an API response like this

let data = {
          "year": 2021,
          "monthValue": 11,
          "dayOfMonth": 9
         }

I have to covert this above object into this format MM/DD/YYYY.

Can convert the above data using string interpolation like this ${data.dayOfMonth}/${data.monthValue}/${data.year} But is there any other way we can use libraries to get this work done.

For e.g in the above string interpolation method, can't able to add 0 at the beginning of the dayOfMonth and monthValue when they are given as single digits.

can we achieve this using moment or date-fns?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

兮颜 2025-02-20 21:24:22

您不需要库即可零 - pad 1-2位数字:

function pad2 (n) {
  return String(n).padStart(2, '0');
}

function format (data) {
  return `${pad2(data.monthValue)}/${pad2(data.dayOfMonth)}/${data.year}`;
}


const data = {
  "year": 2021,
  "monthValue": 11,
  "dayOfMonth": 9,
};

const result = format(data);
console.log(result); // 11/09/2021

You don't need a library just to zero-pad a 1–2 digit number:

function pad2 (n) {
  return String(n).padStart(2, '0');
}

function format (data) {
  return `${pad2(data.monthValue)}/${pad2(data.dayOfMonth)}/${data.year}`;
}


const data = {
  "year": 2021,
  "monthValue": 11,
  "dayOfMonth": 9,
};

const result = format(data);
console.log(result); // 11/09/2021

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文