Sunday, April 12, 2015

JavaScript Date, Time and Live Clock


Date, time, and creating a live clock in JavaScript.

If you were like me, before I learned JavaScript, one of the most eager things I wanted to know was how to access the time using JavaScript-displaying it, working with it and so on. Well, it was, in fact very easy, and I'll tell you why. JavaScript already has a built in object that gets the date and time for you -all you have to do is use it!

Date Object :

To use this date object, you need to first create an instance of it. Uh? Instant noodles? Well, not quite. What we have to do is tell JavaScript to activate this object:
To activate a Date Object so you can use it, do this:

                              var myDate = new Date();

Whenever you want to create an instance of the date object, use this important word: new followed by the object name(). Now, I'm going to list some of the methods of the date object that you can use:

Some methods for the date object:

getDate()  ---  returns the day of the month.

getDay()   --- Returns the day of the week.

getHours() --- Returns the hour(Starts from 0-23)

getMinutes() --- Returns the minutes

getSeconds() --- Returns the seconds 

getMonth() --- Returns the month (Starts from 0 - 11)

getFullYear() --- Returns the year

getTime() ---  Returns the complete time( in really weird format)

Ok, lets say we want to write out today's date:

var todayDate = new Date()
var myYear = todayDate.getFullYear()
var myMonth = todayDate.getMonth() + 1;
var today = todayDate.getDate();

console.log("Today's date is :",myYear+"/"+ myMonth" "/"+ today)

OUTPUT : Today's date is : 2015/4/12


The above output may change based on the current day.

We added "1" to the month, since in JavaScript, it counts months starting from "0", not "1".

The date() object of JavaScript always uses the user's local PC's date and time for its information. So different users may see a different date/time, depending on where in the World he/she is located.

For Above Example : Try this jsfiddle -- In jsfiddle after run the script, see the console for the output.

Displaying a different image depending on the time of the day:


With the above knowledge, and a little HTML, you can display different images according to the date/time. Here is a common example: Displaying a different image depending on whether it is mourning or night.
Lets first get two images: (One for mourning, one for night.)

HTML:
                       <div id="Date"></div>
JS:
                        var current = new Date()
                        var day_night = current.getHours()
                        if (day_night <= 12) {
                               $("#Date").append("<img src='day.jpg'>")
                        } else {
                               $("#Date").append("<img src='night.jpg'>")
                        }

There is one very important concept here:

Take a look at the two lines highlighted. What we have done here is dynamically written out the html code required to display an image (not to be mistaken with dynamic html). Here is where JavaScript becomes amazing. You don't have to hard code your html tags into your webpage- allow JavaScript to think and append it to Date ID  for you.

So basically, if its mourning (before noon), "day.gif" will be shown, and at night, "night.gif."

Example for above Code : Try this jsfiddle

Adding a live clock with the help of a form:

Adding a live clock using forms is quite simple. The basic concept is to continuously write to a form field every 1 second, using the updated time from your own computer. 

HTML :

                         <form name="Tick">
                             <input type="text" size="12" name="Clock">
                         </form>

JS :

                  $(document).ready(function () {
                      window.show = function () {
                        var Digital = new Date()
                        var hours = Digital.getHours()
                        var minutes = Digital.getMinutes()
                        var seconds = Digital.getSeconds()
                       var dn = "AM"
                  if (hours >  12) {
                       dn = "PM"
                     hours = hours - 12  //this is so the hours written out is in 12-hour format, instead                   of the default //24-hour format.
               }
               if (hours == 0) { 
                 hours = 12
               }
        //this is so the hours written out when hours=0 (meaning 12a.m) is 12
              if (minutes <= 9){
                  minutes = "0" + minutes
               }
              if (seconds <= 9){
                seconds = "0" + seconds
              }
        document.Tick.Clock.value = hours + ":" + minutes + ":" + seconds + " " + dn
        setTimeout("show()", 1000)
    }
    show();
});

To Know about setTimeOut and setInterval with examples . Understanding setTimeout and setInterval

Believe it or not, that's all there really is to it!

We first set "dn=AM". If the hours is > 12, meaning its afternoon, we set "dn=PM". If minutes/seconds is greater than 9, we added a "0" to it...why? because we want to pad it, just to make it look better. That's the basic structure of function show()

The most important part, the setTimeout method, was already discussed prior to this page. Basically, this script is run every one second, which gives the illusion that the clock is actually ticking.

Remember, the format of hours in JavaScript is from 0~23, not 1~24! That's the reason why we set it to display "12" whenever hours=0.

For Live Clock : Try this jsfiddle

Unknown Software Engineer

No comments:

Post a Comment