簡體   English   中英

ES6 解構日期

[英]ES6 Destructuring dates

有沒有辦法解構日期?

我知道對於對象,你可以做這樣的事情。

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到一個月。

盡管您可以將 getter 直接添加到Date對象,但這是一種不好的做法。 您可以在此線程中了解更多信息 - 為什么擴展本機對象是一種不好的做法? .

 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)));

實際上是的,您可以解構 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'));

這些是唯一可以在沒有防御的情況下解構的方法。 getMonth()getYear()等方法必須定義一個new Date 但是,您可以計算毫秒轉換為什么(比如now()/1000返回seconds )。 但是進行准確的轉換將是一個挑戰。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM