Paul Clift
Paul Clift

Reputation: 169

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;

Upvotes: 0

Views: 237

Answers (3)

Andy G
Andy G

Reputation: 19367

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));

Upvotes: 0

dashton
dashton

Reputation: 2704

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

Upvotes: 1

Related Questions