JS for Date one year from now

  • 19 June 2019
  • 2 replies
  • 180 views

Hello,

is there anyone that would be able to help me with JS for a Date one year from now displayed in text. the format should be like this: June 19th, 2020

Thank you!


2 replies

Hey Jan!

To grab the date one year from today you can use the Date object provided by the javascript standard library along with some of the functions that are provided out of the box.

new Date(new Date().setFullYear(new Date().getFullYear() + 1))

> Sun Jun 28 2020 15:38:25 GMT-0700 (Pacific Daylight Time)

Because in your case you are looking for a more refined date you might want to go with something like:

var date = new Date();
date.getMonth() + " " + date.getDate() + " " + (date.getFullYear() + 1);

> "5 28 2020”

Now its time to convert your numbered month into a string:

var months = ["January", "February", "March", "April", "May", "June",
  "July", "August", "September", "October", "November", "December"
];

var date = new Date();

months[date.getMonth()] + " " + date.getDate() + " " + (date.getFullYear() + 1);

> "June 28 2020”

I see there is one more requirement here which is adding the suffix to the day of the week. We will use a function for this.

var months = ["January", "February", "March", "April", "May", "June",
  "July", "August", "September", "October", "November", "December"
];

var date = new Date();

function day_suffix(day) {
    var j = day % 10,
        k = day % 100;
    if (j == 1 && k != 11) {
        return day + "st";
    }
    if (j == 2 && k != 12) {
        return day + "nd";
    }
    if (j == 3 && k != 13) {
        return day + "rd";
    }
    return day + "th";
};

months[date.getMonth()] + " " + day_suffix(date.getDate()) + " " + (date.getFullYear() + 1);

> "June 28th 2020"

Hope this helps 🙂

Cheers

Hey Kieran,

thank you for your help here, I was able to solve it actually few days after I posted that. Much appreciate your help!

Jan

Reply