简体   繁体   English

ES6 解构日期

[英]ES6 Destructuring dates

Is there a way to destructure dates?有没有办法解构日期?

I know for objects you can do something like this.我知道对于对象,你可以做这样的事情。

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

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

Is there a better way to do the following in ES6?在 ES6 中是否有更好的方法来执行以下操作? Does something like object destructuring exist for this?是否存在对象解构之类的东西?

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

You can create an object that inherits from the Date object, add getters for month, day, and year, and then you can destructure it.您可以创建一个继承自Date对象的对象,为月、日和年添加 getter,然后您可以对其进行解构。 Although it has some overhead, this might be worthwhile if you use dates a lot.尽管它有一些开销,但如果您经常使用日期,这可能是值得的。 In addition, you can fix things, like the need to add 1 to month.另外,你可以修复一些东西,比如需要加1到一个月。

Although you can add the getters directly to the Date object, this is a bad practice.尽管您可以将 getter 直接添加到Date对象,但这是一种不好的做法。 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)));

Actually yes you can destructure Date(), but youre only limited to a few methods.实际上是的,您可以解构 Date(),但仅限于几种方法。

    let {now,UTC,parse} = Date, {log} = console;

    //returns current time in milliseconds
    log(now());

    //returns a date format for UTC
    log(UTC(96, 1, 2, 3, 4, 5));

    //parses a date to milliseconds
    log(parse('04 Dec 1995 00:12:00 GMT'));

These are the only methods that CAN be deconstructed without defenition.这些是唯一可以在没有防御的情况下解构的方法。 Methods like getMonth() , getYear() , and the like HAVE to have a new Date defined.getMonth()getYear()等方法必须定义一个new Date However you can calculate instead what milliseconds convert to (say now()/1000 returns seconds ).但是,您可以计算毫秒转换为什么(比如now()/1000返回seconds )。 But having an ACCURATE conversion will be a challenge.但是进行准确的转换将是一个挑战。

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

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