2

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? Does something like object destructuring exist for this?

function getFormattedDate(date) {
    return `${date.getMonth() + 1}/${date.getDate()}/${date.getFullYear()}`;
}
huihuihui
  • 189
  • 4
  • 13
  • 4
    If the properties are functions and need to be called, destructuring isn't really an option. – Felix Kling Dec 18 '16 at 08:42
  • What exactly is wrong with the code you already have? – Michał Perłakowski Dec 18 '16 at 12:37
  • You should not be formatting dates yourself. Instead, use [`Intl.DateTimeFormat`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DateTimeFormat) with a locale of `en-US`. –  Dec 18 '16 at 13:43
  • There is nothing wrong with my code. I was just wondering if there is a feature I'm missing or don't know about since it feels very similar to object destructuring. – huihuihui Dec 18 '16 at 17:35

2 Answers2

5

You can create an object that inherits from the Date object, add getters for month, day, and year, and then you can destructure it. 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.

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)));
Community
  • 1
  • 1
Ori Drori
  • 183,571
  • 29
  • 224
  • 209
0

Actually yes you can destructure Date(), but youre only limited to a few methods.

    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. However you can calculate instead what milliseconds convert to (say now()/1000 returns seconds). But having an ACCURATE conversion will be a challenge.

Gareth Compton
  • 159
  • 1
  • 12