momentjs startOf does not work on existing date ob

2019-02-25 20:33发布

问题:

I'm trying to use moment to get the start of a day. I get different results with the following:

moment().startOf('day'); //good
moment(new Date()).startOf('day'); //this does not work!

fiddle: https://jsfiddle.net/y1of77wx/

The practical case is that I'm doing this in a function that takes in a date object as an argument:

function doWork(dt) {
   return moment(dt).startOf('day');
}

I'm sure the solution is simple but I'm just missing something.

回答1:

I suggest to use format() to display the value of a moment object.

As the Internal Properties guide states:

Moment objects have several internal properties that are prefixed with _.

The most commonly viewed internal property is the _d property that holds the JavaScript Date that Moment wrappers. Frequently, developers are confused by console output of the value of _d.

...

To print out the value of a Moment, use .format(), .toString() or .toISOString()

Here a snippet showing the correct results:

console.log(moment().startOf('day').format());
console.log(moment(new Date()).startOf('day').format());
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.18.1/moment.min.js"></script>



标签: momentjs