admin管理员组

文章数量:1418025

I am trying to get the start of and end of day. Below is my code.

var m = moment(new Date('Fri Aug 8 2017 11:31:08 GMT+0530 (India Standard Time)')).startOf('day')
    
console.log(m);    
    
var n = moment(new Date('Fri Aug 8 2017 11:31:08 GMT+0530 (India Standard Time)')).endOf('day')

console.log(n.format()); 
<script src=".js/2.18.1/moment.min.js"></script>

I am trying to get the start of and end of day. Below is my code.

var m = moment(new Date('Fri Aug 8 2017 11:31:08 GMT+0530 (India Standard Time)')).startOf('day')
    
console.log(m);    
    
var n = moment(new Date('Fri Aug 8 2017 11:31:08 GMT+0530 (India Standard Time)')).endOf('day')

console.log(n.format()); 
<script src="https://cdnjs.cloudflare./ajax/libs/moment.js/2.18.1/moment.min.js"></script>

I even tried

moment(new Date('Fri Aug 8 2017 11:31:08 GMT+0530 (India Standard Time)')).startOf('date')

Nothing seems to work. Does moment support this functionality.

Share Improve this question edited Aug 18, 2017 at 8:24 Maclean Pinto asked Aug 18, 2017 at 6:23 Maclean PintoMaclean Pinto 1,1353 gold badges17 silver badges44 bronze badges 4
  • You need the start day without time? – Ashish Lohia Commented Aug 18, 2017 at 6:37
  • 1 If you are using moment.js you should also use it for parsing date strings, see Why does Date.parse give incorrect results? You should not use the built-in parser. – RobG Commented Aug 18, 2017 at 6:41
  • 1 I've converted our code to a runnable snippet and it "works" (though it is unreliable). Please explain how you determined that it doesn't work. Note that depending on the host timezone, the date and time in the OP may fall on a different date (e.g. where the offset is -0700). – RobG Commented Aug 18, 2017 at 6:46
  • Hi Rob, when i use format() it works. Remove format and console the result. – Maclean Pinto Commented Aug 18, 2017 at 8:26
Add a ment  | 

1 Answer 1

Reset to default 4

It does work with the latest version of moment. Check the snippet.

Also if you want to format the time in IST you can apply a fixed UTC offset and format the date in the desired format.

var st = moment(new Date('Fri Aug 8 2017 11:31:08 GMT+0530 (India Standard Time)')).startOf('day').utcOffset("+05:30").format()
console.log(st);

var end = moment(new Date('Fri Aug 8 2017 11:31:08 GMT+0530 (India Standard Time)')).endOf('day').utcOffset("+05:30").format()
console.log(end);
<script src="https://cdnjs.cloudflare./ajax/libs/moment.js/2.18.1/moment.min.js"></script>

本文标签: javascriptGet start of a given date using momentjsStack Overflow