Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
423 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 Reply

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>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...