如何使用JSON字符串化JavaScript新日期

7xllpg7q  于 4个月前  发布在  Java
关注(0)|答案(4)|浏览(70)

当用户填写日历时,我从表单的JSON中获取数据

const data= JSON.stringify(orderForm.informationDate));

字符串
目前,我从JSON中获取数据,以任何方式打印PDF:

{"year":2023,"month":12,"day":22}


如何将数据转换为DD.MM.YYYY格式?

liwlm1x9

liwlm1x91#

建议不要以dd.mm.yyyy格式存储日期,但如果您坚持

const orderForm = { informationDate: {"year": 2023, "month": 12, "day": 22} };

const ddmmyyyy = Object.values(orderForm.informationDate)
  .reverse()
  .map(val => String(val).padStart(2, '0'))
  .join('.');

console.log(ddmmyyyy); // Outputs: 22.12.2023

// With a replacer function

const replacer = (key, value) => {
  if (key === 'informationDate')
    return Object.values(value)
      .reverse()
      .map(val => String(val).padStart(2, '0'))
      .join('.');
  return value;
}

const jsonString = JSON.stringify({ orderForm }, replacer, 2);
console.log(jsonString);

字符串

uidvcgyl

uidvcgyl2#

你的问题是基于一些误解:
1.日期不能序列化到/从JSON -没有日期/时间数据类型。
1.当你向json序列化器提供一个日期时,你就是在提供一个对象,因此序列化器会生成一个对象表示,就像你看到的:

const myFakeDate = { year: 2023, month: 12, day: 22 };
console.log(JSON.stringify(myFakeDate)); // => {"year":2023,"month":12,"day":22}

字符串
1.您在问题中提到的格式显然是字符串,因为日期通常在内部存储为数字,而不是字符串
1.在你的情况下,你有两个选择:
1.在调用JSON.stringify

const data= {
   name: "John Doe",
   birthDate: {year: 1982, month: 3, day: 4}
};

data.birthDate = data.birthDate.day + '.' + data.birthDate.month + '.' + data.birthDate.year;

console.log(JSON.stringify(data));

之前将日期/时间对象转换为字符串
1.或者使用“浏览器”功能:

const data= {
   name: "John Doe",
   birthDate: {year: 1982, month: 3, day: 4}
};

const replacer = function(item) {
   if (item.year && item.month && item.day) {
     return item.day + '.' + item.month + '.' + item.year;
   }

   return item;
};

console.log(JSON.stringify(data, replacer));

1.请记住,您可能需要在另一端反转该过程(例如,将字符串转换回日期)
1.如果你使用的是日期时间对象(而不是普通对象),你可以检查对象类而不是日/月/年属性的存在。这取决于你的具体代码。

cig3rfwq

cig3rfwq3#

你可以得到这个对象的属性(data.year,data.month,data.day)并连接成一个字符串
第一个月

dly7yett

dly7yett4#

1.使用解构的力量
1.格式函数的作用是确保像2这样的日期和月份变成02

const date = {year: 2023, month: 12, day: 22};
const { year, month, day } = date;
const format = (str) => String(str).padStart('0', 2);
const formattedDate = `${format(day)}.${format(month)}.${year}`;
const jsonData = JSON.stringify(formattedDate);
console.log(formattedDate);
console.log(jsonData);

字符串

相关问题