WDN Logo

home-icon Home / JavaScript / Formatting time using JavaScript

Formatting time using JavaScript

Formatting time using JavaScript

Format #7: Correct Time with AM and PM

<script type="text/javascript">
<!--

var a_p = "";
var d = new Date();

var curr_hour = d.getHours();

if (curr_hour < 12)
   {
   a_p = "AM";
   }
else
   {
   a_p = "PM";
   }
if (curr_hour == 0)
   {
   curr_hour = 12;
   }
if (curr_hour > 12)
   {
   curr_hour = curr_hour - 12;
   }

var curr_min = d.getMinutes();

document.write(curr_hour + " : " + curr_min + " " + a_p);

//-->
</script>

The code above is quite simple. First, a variable a_p is initialized. Depending upon the value of curr_hour, we assign AM or PM to this variable.
We then change the value of curr_hour. If the value is 0 (as in the case of 12:40 am), curr_hour shall hold the value of 12. Also, if curr_hour is more than 12 we subtract 12 from it to convert the hours to 12 hour format.

Sponsored Links

However, we still haven’t solved the problem of single digit minutes. When the value returned from getMinutes() is a single digit, we want JavaScript to add a leading zero.

The code above prints:

Format #8: Two digit minutes

To add a leading zero, we first have to check the value returned from getMinutes(). We then convert this numeric value to a string and check its length. If the length is 1, we add a leading zero.

<script type="text/javascript">
<!--

var a_p = "";
var d = new Date();
var curr_hour = d.getHours();
if (curr_hour < 12)
   {
   a_p = "AM";
   }
else
   {
   a_p = "PM";
   }
if (curr_hour == 0)
   {
   curr_hour = 12;
   }
if (curr_hour > 12)
   {
   curr_hour = curr_hour - 12;
   }

var curr_min = d.getMinutes();

curr_min = curr_min + "";

if (curr_min.length == 1)
   {
   curr_min = "0" + curr_min;
   }

document.write(curr_hour + " : " + curr_min + " " + a_p);

//-->
</script>

JavaScript is a loosely-type language. It means that the data type of a variable can be easily changed. Hence, the same variable storing a number can be made to store a string value.
Here we add a blank string to curr_min variable. This operation converts the data type of this variable from number to a string. Using the length property of the string object, we can then check the number of digits. If the number of digits are one, a leading zero is attached to the variable.

The code above prints:

Sponsored Links

Search

Your comments
Star icon IMPORTANT Have a question / problem? Click here to ask an expert.

Sponsored Links

Tips

How do I view a deleted web page?
Is there a way to view a deleted web page - one that is no longer available? Yes there is and the solution is quite simple. [more...]

Fact

By September 2012, Apple had sold more than 350 million iPods. [more...]

Share on Whats app Share on Facebook Share on Twitter Share on Google plus