Dealing with dates in js – there must be an easier way?

问题内容:

I have been trying to do something for the past hours that really should be easier. (It’s the easiest thing in the world with my beloved PHP….. but I need it in JS.)
All I need to do is to output various dates relative to the present date (all in YYYY-mm-dd) ….

var today = TODAY’S DATE

var tomorrow = TOMORROW’S DATE

var end_of_this_week = DATE OF THE FINAL DAY (SUNDAY) OF THE CURRENT WEEK

var start_of_next_week = DATE OF THE FIRST DAY (MONDAY) OF NEXT WEEK

var end_of_this_month = DATE OF THE FINAL DAY OF THE CURRENT MONTH

var start_of_next_month = DATE OF THE FIRST DAY OF NEXT MONTH

var end_of_next_month = DATE OF THE FINAL DAY OF NEXT MONTH

That’s it. I know about the ‘Datejs’ package but (no offence) I found it to be a big mess. I’ve poured over this (and other) forums looking for an answer to this, and while there are a few useful bits and pieces around, I ended up with more bugs (e.g. 13 months in a year) than anything else. I think that if someone with the know-how could come up with an elegant solution, it would be very useful for lots of people.

Here is the foundation from which all of this stuff may be derived:

    var date_default = new Date(new Date().getTime());
    var day_now = date_default.getDate();
    var month_now = date_default.getMonth()+1;
    var year_now = date_default.getFullYear();

    var today = year_now+'-'+month_now+'-'+day_now;

问题评论:

1  
Look at Moment.js.
1  
new Date(new Date().getTime()) is exactly the same as new Date()
    
There really isn’t, dates are complicated, but there are libraries, like Moment, that simplify things.
    
Read this gem: FalsehoodsAboutTime.com 😉
    
Thomas Kleßen: 😀
– Paul Clift
2 mins ago

答案:

答案1:

I’ve found momentJs to be the cleanest library for dealing with date and time manipulation in js.

e.g for your tomorrow you could do:

const tomorrow = moment().add(1, 'days').format('YY-MMM-dd');

Docs here : docs

答案评论:

    
Yes, it looks really great! I hadn’t come across it until now.
– Paul Clift
3 mins ago

答案2:

It is possible to obtain the values you need although, as mentioned, this isn’t straightforward with vanilla JS. For example,

var today = new Date();

var tomorrow = new Date(today.setDate(today.getDate()+ 1));

答案评论:

答案3:

These are few libraries that you might be interested in:

答案评论:

原文地址:

https://stackoverflow.com/questions/47756214/dealing-with-dates-in-js-there-must-be-an-easier-way

添加评论