0

As the title says I want to dynamically assign today's date as string in "DD/MM/YYYY" format to the property. It has to be dynamically calculated and assigned right next to the objects property declaration.

I figured something like this:

var obj = {
    today: `${(new Date).getDate()}/${(new Date).getMonth()}/${(new Date).getFullYear()}`
};

Which works perfect BUT it's obviously not efficient as it creates three new Date instances. I would like to do it something like this:

var obj = {
    today: (
        const today = new Date;
        return `${today.getDate()}/${today.getMonth()}/${today.getFullYear()}`
    )
};

Thanks!

mairisb
  • 23
  • 6
  • 1
    Possible duplicate of [How to get current formatted date dd/mm/yyyy in Javascript and append it to an input](https://stackoverflow.com/questions/12409299/how-to-get-current-formatted-date-dd-mm-yyyy-in-javascript-and-append-it-to-an-i) – mayersdesign Feb 08 '19 at 12:50

2 Answers2

3

What you're looking for is an IIFE (Immediately Invoked Function Expression): basically, you want to wrap the entire generator function and invoke it immediately when the object is defined:

var obj = {
    today: (() => {
        const today = new Date;
        return `${today.getDate()}/${today.getMonth()}/${today.getFullYear()}`
    })()
};

console.log(obj);

On a side note:

See updated example here:

function pad(val) {
  return val.toString().padStart(2, '0');
}

var obj = {
    today: (() => {
        const today = new Date;
        return `${pad(today.getDate())}/${pad(today.getMonth() + 1)}/${today.getFullYear()}`
    })()
};

console.log(obj);
Terry
  • 63,248
  • 15
  • 96
  • 118
0
var today = new Date();
var obj = {
 today:(
   return `${today.getDate()}/{today.getMonth()}/${today.getFullYear()}`
)
}

should be work

Nico Zimmer
  • 325
  • 1
  • 12