javascript - ES6 解构日期

标签 javascript ecmascript-6

有没有办法解构日期?

我知道对于对象你可以做这样的事情。

var o = {p: 42, q: true};
var {p, q} = o;

console.log(p); // 42
console.log(q); // true

在 ES6 中是否有更好的方法来执行以下操作?是否存在像对象解构这样的东西?

function getFormattedDate(date) {
    return `${date.getMonth() + 1}/${date.getDate()}/${date.getFullYear()}`;
}

最佳答案

您可以创建一个继承自 Date 对象的对象,添加月、日和年的 getter,然后可以对其进行解构。尽管它有一些开销,但如果您经常使用日期,这可能是值得的。此外,您还可以修复一些问题,例如需要在月份中添加 1。

Although you can add the getters directly to the Date object, this is a bad practice. You can more about it in this thread - Why is extending native objects a bad practice?.

class EDate extends Date {  
  get month() {
    return this.getMonth() + 1;
  }
  
  get day() {
    return this.getDate();
  }
  
  get year() {
    return this.getFullYear();
  }
}

const getFormattedDate = ({ month, day, year }) => `${month}/${day}/${year}`

console.log(getFormattedDate(new EDate()));

// since Date can receive another Date as input, you can do this as well

const date = new Date();

console.log(getFormattedDate(new EDate(date)));

关于javascript - ES6 解构日期,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41206725/

相关文章:

javascript - ES6 : Restricting the Base Class to a Singleton

javascript - ES6 模块导入和依赖管理

javascript - Ext Js 和 Adob​​e Air

JavaScript 引用错误 : x is not defined

当选项卡不活动时 JavaScript 不工作

javascript - 特定窗口大小的触发功能

javascript - 当react native出现这个错误时: transformClassesWithDexBuilderForDebug?

javascript - 结果中仅出现数组中的一个值

javascript - for循环计数器可以在ES2015中声明为const吗?

javascript - 从 ES6 生成器创建数组