ArtsAutosBooksBusinessEducationEntertainmentFamilyFashionFoodGamesGenderHealthHolidaysHomeHubPagesPersonal FinancePetsPoliticsReligionSportsTechnologyTravel

Using the date in javascript

Updated on August 6, 2014

What can I do with the date?

There are a lot of fun things you can do with the date in Javascript. For example, you could make a background that changes to reflect the season: snowflakes in the winter, and red leaves in the fall. You could also make an image that changes randomly every day. Perhaps even a message that only shows up on certain dates to wish them happy holidays! There are a lot of other things you can do, you just need to use your imagination.

But before we begin,

Here's an example that shows the sort of things we'll be doing.

Getting the date

Before we can talk about actually using the date in javascript, first we need to actually get the date. Thankfully, this is incredibly easy.

var date = new Date();

var weekday = date.getDay();
var month = date.getMonth();
var day = date.getDate();
var year = date.getFullYear();

The first line is the most important here. We're creating a new Date object, which automatically records the current date and time, and storing it into a variable named date.

Creating the weekday, month, day, and year variables isn't necessary, but doing so will bring us great convenience later on.

There are a lot of methods you can use to get different parts of the date, but these four are probably the most common you'll use:

  • getDay returns a number representing the weekday, where 0 is Sunday and 6 is Saturday.
  • getMonth returns a number representing the current month, where 0 is January and 11 is December.
  • getDate returns a number representing the current day of the month, from 1 to 31.
  • getFullYear simply returns the current year.

For full documentation on the Date object look here.

Printing the date

The absolutely easiest way to print the date:

document.write(date);

Should write something like this:

    Mon Jul 21 2014 19:38:09 GMT-0400 (Eastern Daylight Time)

But this doesn't look too pretty for most applications, so I'll show you how to print the date in any format you please.

To start simple, let's just print the date in number form.

document.write((month+1)+"/"+day+"/"+year);

This should print something along the lines of "7/19/2014".

Note that we added 1 to the month so that it would give the correct number.

The numeric date works, but it's quite minimal. It'd be nice if we could get some words in there, but the date object only gives us numbers.

So let's create an array that contains the names of each month. While we're add it, let's add the weekday as well.

var weekdays=["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"];
var months=["January","February","March","April","May","June","July","August","September","October","November","December"];

Now to print the date using the names for the weekdays and months, we just need to do this:

document.write(weekdays[weekday]+", "+months[month]+" "+day+", "+year);

This should print something along the lines of "Saturday, July 19, 2014".

Note that this time we don't add 1 to the month. This is because arrays start at 0, so January would be "months[0]".

This looks really good, but if you want to be really fancy then there's one more thing we can do to dress up the date even more. We can add an ordinal suffix.

The ordinal suffix is the two letters the come after numbers such as 1st, 2nd, and 3rd.

Oridinal suffixes aren't too complicated, but there's a few special exceptions that make them tricky. For your convenience, I've made a special function for adding the ordinal suffix to numbers. Just for you.

function ordinal(N){
    N = N.toString();
    if (N.slice(-1) === '1' && N.slice(-2) !== '11'){
        return N+"<sup>st</sup>"
    }else if (N.slice(-1) === '2' && N.slice(-2) !== '12'){
        return N+"<sup>nd</sup>"
    }else if (N.slice(-1) === '3' && N.slice(-2) !== '13'){
        return N+"<sup>rd</sup>"
    }else{
        return N+"<sup>th</sup>"
    }
}

It takes a number as a parameter and converts it to a string. It then checks the last two characters in the string to see whether it ends in 1 but not 11, 2 but not 12, or 3 but not 13. It then returns a string containing the number with the appropriate ordinal suffix. It also wraps the suffix in <sup> tags to make it superscript, but you can remove these if you don't like them.

And to use it:

document.write(weekdays[weekday]+", "+months[month]+" "+ordinal(day)+", "+year);

This should return something similar to "Saturday, July 19th, 2014".

It looks quite nice, I think.

Checking the date

So now we have declared the date object, and we know how to print out the date. But to do more fancy stuff, we'll need to know how to check what date it is. This is really simple:

if (month==11 && day==25){
    alert(Merry Christmas!);
}

As you can see, here we're checking whether it's Christmas and showing the user a message if it is.

You can also do the same thing for the weekday and the year, and any other date method.

Beware that the month and weekday start at zero, as this means January is month zero and December is month eleven. You can add 1 to the month while checking it if you want. For example, "month+1==12" would check for december.

If you wish, I've made a little function for your convenience that will make it a little easier to check what date or month it is.

Date.prototype.test = function(month, day, year){
    //handle the parameters
    month = typeof month !== 'undefined' ? month : 0;
    day = typeof day !== 'undefined' ? day : 0;
    year = typeof year !== 'undefined' ? year : 0;
    //check the month, day, and year
    if (month>0 && month !== this.getMonth()+1) return false;
    if (day>0 && day !== this.getDate()) return false;
    if (year>0 && year !== this.getFullYear()) return false;
    return true;
}

The function takes three parameters, all of which are optional. The three parameters are month, day and year, and it checks to make sure they are the same as the current date. If they are, it returns true. Else it returns false.

To use it to check only the month, you do this: "date.test(1)", where 1 is a number between 1 and 12. In this case we're checking for January.

To check for both day and month, you do this: "date.test(2,29)" Where 29 is a number between 1 and 31, corresponding to the day of month. Here we're checking for February 29th.

To check for only the day or only the year, you can place zeros in the other parameters. My function will ignore parameters that are zero. For example, "date.test(0,0,2015)" Will test for only the year 2015.

Checking a range of dates

My function is good for checking for specific months or dates, but it's not good for checking ranges. Unfortunately checking ranges of dates can sometimes be rather complicated, so for your convenience I've made yet another useful function!

Date.prototype.range = function(month1,day1,year1,month2,day2,year2){
    //handle the parameters
    month1 = (typeof month1!=='number' || month1===0) ? this.getMonth()+1 : month1;
    day1 = (typeof day1!=='number' || day1===0) ? this.getDate() : day1;
    year1 = (typeof year1!=='number' || year1===0) ? this.getFullYear() : year1;
    month2 = (typeof month2!=='number' || month2===0) ? this.getMonth()+1 : month2;
    day2 = (typeof day2!=='number' || day2===0) ? this.getDate() : day2;
    year2 = (typeof year2!=='number' || year2===0) ? this.getFullYear() : year2;
    //convert the first and second date into a number
    var date1 = Date.parse(month1+"/"+day1+"/"+year1);
    var date2 = Date.parse(month2+"/"+day2+"/"+year2);
    //get the current date and convert it into a number
    var cdate = Date.parse((this.getMonth()+1)+"/"+this.getDate()+"/"+this.getFullYear())
    //compare the dates
    return date1 <= cdate && cdate <= date2;
}

This one takes six parameters. The first three are the month, day, and year of the first date, and the second three are the month, day, and year of the second date. Any parameters that are either missing or zero will be set to the current date.

Like with the last function I made for you, the month parameters should be from 1 to 12.

This function converts the two dates into a format which is the number of miliseconds since January 1st, 1970 to make them easier to compare. If the current date is greater than or equal to the first date and less than or equal to the second date, then it returns true. Else it returns false.

Here is an example usage:

if (date.range(6,21,0,9,20,0)){
    alert("It's summer!");
}

Here we test whether the date is between the 21st of June and the 20th of September, in any year, and send the user a message if it is.

Using the methods above, you have quite a bit of flexibility for making code run only on certain dates, months, and seasons. You can easily target static holidays like Halloween and Christmas, but some holidays which change their date every year, such as Easter, will be a bit more difficult. Unfortunately I can't tell you how to target these dynamic holidays, as each one of them will need to be calculated in a different way.

Using the date

Now that you know how to get and check the date, it's time for the most exciting part.

Our first use will be to change the website's background based on the month or season.

if (date.test(5)){
    document.body.style.backgroundImage="url(may.jpeg)"
}

Here I used the function date.test I made which I showed you above. If you decide not to use my function, then remember that you can also check the month the traditional way by using "date.getMonth()+1==5".

If the month is May, then the script changes the background image of the body of the webpage to the URL specified. You aren't limited to just changing the background image though, you can change any style of any element you want. For a full list of style attributes you can modify, see here. The styles are the same as CSS styles, but some of them have slightly different names.

Making it random

Next we'll be making an image that changes randomly every day. In essence, an "Image of the day".

But before that we'll need a better random number generator. We'll be using a script called "seedrandom" which will allow us to provide the random number generator with a "seed". When you give it the same seed, it gives you the same random numbers. We'll be using the current date as the seed, which will mean it will give us the same image as long as the date doesn't change.

The actual script can be found through this link, so be sure to include it on your webpage.

The markup

<img src="default.png" alt="Image of the day" id="imageoftheday">

<script src="http://davidbau.com/encode/seedrandom.js">

The script

var images = ["1.png","2.png","3.png","4.png","5.png","6.png"];

Math.seedrandom(month+"/"+day+"/"+year);

var index = Math.floor(Math.random()*images.length);

document.getElementById("imageoftheday").src = images[index];

Math.seedrandom();

First we create an array of all the images available for the image of the day.

Then we seed the random number generator with the current date, and generate an index for our array. This index will be the same every time you refresh the page as long as it's still the same day.

Math.random returns a value between 0 and 1. We multiply it by the length of the images array to make the number between 0 and the length of the array, and then use Math.floor to convert it into an integer.

Finally, we actually change the image. We do this by changing its "src" attribute.

After we're all done, we reset the seed to a random value so that if you use random numbers anywhere else on your page they will work as expected.

The rest is up to you!

This is only touching the surface of what you can do with the date in javascript. With a bit of imagination and the right knowledge, almost anything is possible.

As always feel free to use any script I've shown here without any reservation. And if you have any questions, please leave a comment!

working

This website uses cookies

As a user in the EEA, your approval is needed on a few things. To provide a better website experience, hubpages.com uses cookies (and other similar technologies) and may collect, process, and share personal data. Please choose which areas of our service you consent to our doing so.

For more information on managing or withdrawing consents and how we handle data, visit our Privacy Policy at: https://corp.maven.io/privacy-policy

Show Details
Necessary
HubPages Device IDThis is used to identify particular browsers or devices when the access the service, and is used for security reasons.
LoginThis is necessary to sign in to the HubPages Service.
Google RecaptchaThis is used to prevent bots and spam. (Privacy Policy)
AkismetThis is used to detect comment spam. (Privacy Policy)
HubPages Google AnalyticsThis is used to provide data on traffic to our website, all personally identifyable data is anonymized. (Privacy Policy)
HubPages Traffic PixelThis is used to collect data on traffic to articles and other pages on our site. Unless you are signed in to a HubPages account, all personally identifiable information is anonymized.
Amazon Web ServicesThis is a cloud services platform that we used to host our service. (Privacy Policy)
CloudflareThis is a cloud CDN service that we use to efficiently deliver files required for our service to operate such as javascript, cascading style sheets, images, and videos. (Privacy Policy)
Google Hosted LibrariesJavascript software libraries such as jQuery are loaded at endpoints on the googleapis.com or gstatic.com domains, for performance and efficiency reasons. (Privacy Policy)
Features
Google Custom SearchThis is feature allows you to search the site. (Privacy Policy)
Google MapsSome articles have Google Maps embedded in them. (Privacy Policy)
Google ChartsThis is used to display charts and graphs on articles and the author center. (Privacy Policy)
Google AdSense Host APIThis service allows you to sign up for or associate a Google AdSense account with HubPages, so that you can earn money from ads on your articles. No data is shared unless you engage with this feature. (Privacy Policy)
Google YouTubeSome articles have YouTube videos embedded in them. (Privacy Policy)
VimeoSome articles have Vimeo videos embedded in them. (Privacy Policy)
PaypalThis is used for a registered author who enrolls in the HubPages Earnings program and requests to be paid via PayPal. No data is shared with Paypal unless you engage with this feature. (Privacy Policy)
Facebook LoginYou can use this to streamline signing up for, or signing in to your Hubpages account. No data is shared with Facebook unless you engage with this feature. (Privacy Policy)
MavenThis supports the Maven widget and search functionality. (Privacy Policy)
Marketing
Google AdSenseThis is an ad network. (Privacy Policy)
Google DoubleClickGoogle provides ad serving technology and runs an ad network. (Privacy Policy)
Index ExchangeThis is an ad network. (Privacy Policy)
SovrnThis is an ad network. (Privacy Policy)
Facebook AdsThis is an ad network. (Privacy Policy)
Amazon Unified Ad MarketplaceThis is an ad network. (Privacy Policy)
AppNexusThis is an ad network. (Privacy Policy)
OpenxThis is an ad network. (Privacy Policy)
Rubicon ProjectThis is an ad network. (Privacy Policy)
TripleLiftThis is an ad network. (Privacy Policy)
Say MediaWe partner with Say Media to deliver ad campaigns on our sites. (Privacy Policy)
Remarketing PixelsWe may use remarketing pixels from advertising networks such as Google AdWords, Bing Ads, and Facebook in order to advertise the HubPages Service to people that have visited our sites.
Conversion Tracking PixelsWe may use conversion tracking pixels from advertising networks such as Google AdWords, Bing Ads, and Facebook in order to identify when an advertisement has successfully resulted in the desired action, such as signing up for the HubPages Service or publishing an article on the HubPages Service.
Statistics
Author Google AnalyticsThis is used to provide traffic data and reports to the authors of articles on the HubPages Service. (Privacy Policy)
ComscoreComScore is a media measurement and analytics company providing marketing data and analytics to enterprises, media and advertising agencies, and publishers. Non-consent will result in ComScore only processing obfuscated personal data. (Privacy Policy)
Amazon Tracking PixelSome articles display amazon products as part of the Amazon Affiliate program, this pixel provides traffic statistics for those products (Privacy Policy)
ClickscoThis is a data management platform studying reader behavior (Privacy Policy)