Dieser Artikel wurde - im Gegensatz zu den meisten Artikeln meines Blogs - in Englisch verfasst.
Einer der Gründe dafür könnte sein, dass es sich um einen technischen Artikel handelt, der in englischer Sprache einem breiteren Publikum helfen kann.

Get next day of week in JavaScript – strtotime equivalent

Sometimes it is necessary for coders to get the next monday, tuesday, wednesday orany other day of the week.

As a PHP coder, I can simply use the strtotime()  function in PHP to get a timestamp for, let’s say,  next wednesday. The code would look like this

Now, there is no JavaScript equivalent to PHPs strtotime  function. So I needed to find one or write my own function to get the Date  object of the next occurence of a given day of week.

Here is something I have found on stackoverflow that pretty much did what I needed. I tweaked it a bit to be able to also set hours, minutes and seconds.

This is the original code from stackoverflow.

And here is my tweaked version of this code. I needed this for the Apache Cordova Telerik LocalNotifications Plugin call, that’s why it is called getDateForNotification  :)

So when you need the Date  object for the next Thursday at 15:03:22, you simply call the method as follows:

The first parameter is the day of the week.

The following parameters are hours , minutes  and seconds

The above method call returns (at the time fo writing this)

As you can see, this is not really an equivalent to PHPs strtotime()  function, as it only gets the next occurence for a given day of week. It will not get you „monday in two weeks“ or stuff like that.

But if you need to get the Date  object for the next Saturday at 23:45:22, this method is for you :)

I hope this helps some people out there. If you think you have good additions to be added to this code, let me know in the comments and I will add them.

Veröffentlicht von

Christian Hänsel

Web-Entwickler, SEO-Experte. Ich liebe technisches SEO, die Entwicklung von neuen Ideen und alles rund um das Internet... ja, ich habe mein Hobby zum Beruf gemacht und gehe auch Montags gerne zur Arbeit.

Verfasse einen Kommentar