Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
414 views
in Technique[技术] by (71.8m points)

momentjs startOf does not work on existing date object

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...