I have today = new Date();
object. I need to get first and last day of the current week. I need both variants for Sunday and Monday as a start and end day of the week. I am little bit confuse now with a code. Can your help me?
相关问题
- Is there a limit to how many levels you can nest i
- How to toggle on Order in ReactJS
- void before promise syntax
- Keeping track of variable instances
- Can php detect if javascript is on or not?
You can also use following lines of code to get first and last date of the week:
Hope it will be useful..
The excellent (and immutable) date-fns library handles this most concisely:
SetDate
will sets the day of the month. UsingsetDate
during start and end of the month,will result in wrong weekIf u setting Date is 01-Jul-2014, it will show firstday as 29-Jun-2014 and lastday as 05-Jun-2014 instead of 05-Jul-2014
So overcome this issue i used
I recommend to use Moment.js for such cases. I had scenarios where I had to check current date time, this week, this month and this quarters date time. Above an answer helped me so I thought to share rest of the functions as well.
Simply to get current date time in specific format
Week starts from Sunday and ends on Saturday if we simply use 'week' as parameter for endOf function but to get Sunday as the end of the week we need to use 'isoweek'.
I chose this format as per my need. You can change the format according to your requirement.
The moment approach worked for me for all the cases ( although i have not test the boundaries like year end , leap years ). Only Correction in the above code is the parameter is "isoWeek" , if you want to start the week from Monday.
Be careful with the accepted answer, it does not set the time to 00:00:00 and 23:59:59, so you can have problems.
I recommend using Moment.js to deal with dates. For your case:
This is just a small use case, it's really simple to do a lot of complex operations.
You can see learn more here: http://momentjs.com/