What is the best way to clear time of a browser native date object using Moment.js so that in the current timezone of my browser it's today midnight.
Asked
Active
Viewed 989 times
1
-
2Maybe [`startOf('day')`](http://momentjs.com/docs/#/manipulating/start-of/) is what you are looking for. – VincenzoC Dec 21 '16 at 20:45
-
@VincenzoC - Please provide answers in answer, not in comments. – Matt Johnson-Pint Dec 21 '16 at 22:21
-
Sebastien - Keep in mind that not every local day *has* a midnight. If there is a DST "spring-forward" transition at 00:00, then the day starts at 01:00. This happens in Brazil, and several other places around the world. `startOf('day')` will reflect that. – Matt Johnson-Pint Dec 21 '16 at 22:22
-
@MattJohnson you are right, but I was not sure that I understood what the OP was asking and just tried to give a quick link. I think that a good answer has to include consideration like what you added in the second comment (I was not aware of the _spring-forward_ "issue" with midnight) – VincenzoC Dec 21 '16 at 22:32
1 Answers
2
The closest thing to what you asked is as follows:
var d = new Date(); // your browser native date object
var m = moment(d).startOf('day'); // move to the start of the day in the local time zone
d = m.toDate(); // convert back to a native date object
However, if this is the only thing you want to do, you don't need Moment. Just do:
d = d.setHours(0, 0, 0, 0);
Also, keep in mind that not every local day has a midnight. If there is a DST "spring-forward" transition at 00:00, then the day starts at 01:00. This happens in Brazil, and several other places around the world. In this case, Moment's startOf('day')
function will ensure the result is 1:00, however the setHours
approach may set 1:00, or may set 23:00 on the prior day, depending on browser implementation.

Matt Johnson-Pint
- 230,703
- 74
- 448
- 575