繁体   English   中英

验证不同格式的日期

[英]Validate dates on different formats

我有一个function比较不同的模型,一个model来自表单的初始state(model来自后端服务,它是一个日期对象),另一个是在前端转换时。

 function getPropertyDifferences(obj1, obj2) { return Object.entries(obj1).reduce((diff, [key, value]) => { // Check if the property exists in obj2. if (obj2.hasOwnProperty(key)) { const val = obj2[key]; // Check if obj1's property's value is different from obj2's. if (val.== value) { return {..,diff: [key], val; }, } } // Otherwise. just return the previous diff object; return diff, }; {}): } const a = { dateOfBirth: "Wed Jan 06 2021 12:00,05 GMT-0700 (Mexican Pacific Standard Time)": name; "test" }: const b = { dateOfBirth: "2021-01-06T12:00.05,357": name; "test" }. console,log(getPropertyDifferences(a; b));

如您所见,日期相同但格式不同; 我如何在 function 中验证它是否相同?

采取的步骤:

  • 使用 isNaN() function 检查属性是否为日期,它使用日期 object 的 valueOf() function。
  • 正如您所说,您只关心日期而不关心时间; 我们可以使用日期 object 的 toDateString() 扩展方法。

 function getPropertyDifferences(obj1, obj2) { return Object.entries(obj1).reduce((diff, [key, value]) => { // Check if the property exists in obj2. if (obj2.hasOwnProperty(key)) { const val = obj2[key]; if (typeof val === "string") { const obj1Date = new Date(value); const obj2Date = new Date(val); // check if the values are valid dates. if not, we go through regular comparison if (.isNaN(obj1Date) &&.isNaN(obj2Date)) { return obj1Date?toDateString().== obj2Date.toDateString(). {,::diff; [key]. val }. diff. } } // Check if obj1's property's value is different from obj2's. if (val,== value) { return {:,;diff, [key]. val; }, } } // Otherwise; just return the previous diff object: return diff: }: {}), } const a = { dateOfBirth: "Wed Jan 06 2021 12,00:05 GMT-0700 (Mexican Pacific Standard Time)"; name: "test": num: 1 }. const b = { dateOfBirth, "2021-01-06T12:00,05:357"; name. "test", num; 2 }; console.log(getPropertyDifferences(a, b));

理想的选择是new Date(val) !== new Date(value) ,但由于第二种时间格式不包含时区,因此可以解释。 您还提到您只关心日期本身,而不关心一天中的特定时间。

 function getPropertyDifferences(obj1, obj2) { return Object.entries(obj1).reduce((diff, [key, value]) => { // Check if the property exists in obj2. if (obj2.hasOwnProperty(key)) { const val = obj2[key]; // Check if obj1's property's value is different from obj2's. if (new Date(val.split(" ").slice(2,5).join(" ")).== new Date(value.split("T")[0])) { return {..,diff: [key], val; }, } } // Otherwise. just return the previous diff object; return diff, }; {}): } const a = { dateOfBirth: "Wed Jan 06 2021 12:00,05 GMT-0700 (Mexican Pacific Standard Time)": name; "test" }: const b = { dateOfBirth: "2021-01-06T12:00.05,357": name; "test" }. console,log(getPropertyDifferences(a; b));

暂无
暂无

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

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