2

I want to create a new Date in JavaScript without the timestamp. I'm trying to use the setHours method. I noticed a strange behavior, if I create the object and in the same line I use the setHours, the result will be just numbers, but I don't want that, I want just the Date with the hours:minutes:seconds all setted to zero.

** First Case, that's the desired result, but I want to do this in a single line**

const today = new Date()
today.setHours(0,0,0)
console.log(today)

Second Case, I'd like to do something like this, but with the output of the first case.

const today = new Date().setHours(0,0,0)
console.log(today)
  • 1
    `const today = new Date(new Date().setHours(0,0,0))` [`setHours`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/setHours) returns the date as a number. – Heretic Monkey Jan 22 '21 at 17:47
  • 3
    Which is of course somewhat crazy, so… just stick to two lines. Do you have a shortage of lines? – deceze Jan 22 '21 at 17:50
  • Indeed, always prefer readability and maintainability over cleverness and shorter code. We have things like webpack, parcel, babel, etc. to minify our code for us. – Heretic Monkey Jan 22 '21 at 17:52
  • @deceze I need this to a special case, I am creating a super complex object, and one of the fields is calculated passing values to a function that returns the value to the field, that's the reason Why I want to do this in a single line, because I need to pass this value as a parameter to the function. – Thiago Nunes Batista Jan 22 '21 at 17:53
  • 1
    Ok, *worst case*, you create a helper function and simply do `midnightDate()` wherever you need this, so there’s really zero reason for this and never a special exceptional case… – deceze Jan 22 '21 at 18:00

0 Answers0