10 ways to format time and date using JavaScript

 

JavaScript has an inbuilt support for dates and times with its Date object. The methods of the Date object return various values associated with date and time.

To start working with dates and time, we first initialize a variable and assign it a value with the new operator and the Date() constructor. The main function of the new operator withDate() constructor is to create a new date object that is stored in the variable. Here is the code:

var d = new Date();

Thus, variable d contains a new date object. We can now call the various methods of this date object.

 

Format #1: date-month-year

The three methods that we would be using are:

  • getDate(): Returns the date
  • getMonth(): Returns the month
  • getFullYear(): Returns the year
<script type="text/javascript">
<!--
var d = new Date();
var curr_date = d.getDate();
var curr_month = d.getMonth();
var curr_year = d.getFullYear();
document.write(curr_date + "-" + curr_month + "-" + curr_year);
//-->
</script>

This prints: 29-7-2011

In the code above, we have a different variable for the day, month and year. These variables all contain numeric quantities. (You can check this using typeof()). Hence, you can perform any kind of numerical operations on these variables.

The eagle-eyed would have noticed that the month value returned by getMonth() is one less than the current month. This is because months start at 0 value, thus, January is represented by 0, February as 1, March as 2 ...
We would have to increment the value returned by getmonth() by 1. The corrected lines of code are:

<script type="text/javascript">
<!--
var d = new Date();
var curr_date = d.getDate();
var curr_month = d.getMonth();
curr_month++;
var curr_year = d.getFullYear();
document.write(curr_date + "-" + curr_month + "-" + curr_year);
//-->
</script>

Prints: 29-8-2011

Format #2: month/day/year

This is very similar to the above:

<script type="text/javascript">
<!--
var d = new Date();
var curr_date = d.getDate();
var curr_month = d.getMonth();
curr_month++;
var curr_year = d.getFullYear();
document.write(curr_month + "/" + curr_date + "/" + curr_year);
//-->
</script>

Prints: 8/29/2011

Format #3: date-month name-year (something like, 21-March-2001)

The getMonth() function gives us the month in a numeric form. To convert this value into the month name, we will employ an array. The array would contain all the 12 month names.

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

var m_names = new Array("January", "February", "March", 
"April", "May", "June", "July", "August", "September", 
"October", "November", "December");

var d = new Date();
var curr_date = d.getDate();
var curr_month = d.getMonth();
var curr_year = d.getFullYear();
document.write(curr_date + "-" + m_names[curr_month] 
+ "-" + curr_year);

/* The last two lines above have 
to placed on a single line */

//-->
</script>

Note: For the sake of clarity, I've written the JavaScript code for the array in multiple lines. For usage, you would have to put this on a single line.

This time, we use the new operator with the Array() constructor and store the 12 month names in the array. Variable m_names stores the array of month names.
The value returned by getMonth() is the index at which the month name is stored in the array. Indexes in JavaScript arrays begin at 0; this suits our purpose and we do not need to increment the getMonth() value.

The code above prints: 29-August-2011

Format #4: Like 21st March 2001

In this format we include a superscript to the date value. The idea is to identify the date and then select a superscript based on the date value.

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

var m_names = new Array("January", "February", "March", 
"April", "May", "June", "July", "August", "September", 
"October", "November", "December");

var d = new Date();
var curr_date = d.getDate();
var sup = "";
if (curr_date == 1 || curr_date == 21 || curr_date ==31)
   {   sup = "st";   }
else if (curr_date == 2 || curr_date == 22)
   {   sup = "nd";   }
else if (curr_date == 3 || curr_date == 23)
   {   sup = "rd";   }
else
   {   sup = "th";   }

var curr_month = d.getMonth();
var curr_year = d.getFullYear();

document.write(curr_date + "<SUP>" + sup + "</SUP> " 
+ m_names[curr_month] + " " + curr_year);

//-->
</script>

Note: The last line of code has been split up into two lines. For usage, the entire code should be written on a single line.

We first initialize a variable sup that would store the superscript value. Using If-Else-If, we check the value of the current date and accordingly assign a value to sup.

The code prints: 29th August 2011

Format #5: day date month name year (something like, Wednesday 21st March 2001)

The getDay() method returns a number that specifies the day of the week. Sunday is represented by 0, Monday by 1 and so on. Here again we employ an array. This array would contain the Day names.

<script type="text/javascript">
<!--
var d_names = new Array("Sunday", "Monday", "Tuesday",
"Wednesday", "Thursday", "Friday", "Saturday");

var m_names = new Array("January", "February", "March", 
"April", "May", "June", "July", "August", "September", 
"October", "November", "December");

var d = new Date();
var curr_day = d.getDay();
var curr_date = d.getDate();
var sup = "";
if (curr_date == 1 || curr_date == 21 || curr_date ==31)
   {   sup = "st";   }
else if (curr_date == 2 || curr_date == 22)
   {   sup = "nd";   }
else if (curr_date == 3 || curr_date == 23)
   {   sup = "rd";   }
else
   {   sup = "th";   }
var curr_month = d.getMonth();
var curr_year = d.getFullYear();

document.write(d_names[curr_day] + " " + curr_date + "<SUP>"
+ sup + "</SUP> " + m_names[curr_month] + " " + curr_year);
//-->
</script>

Note: For the sake of clarity, I've written the code for the arrays and the write() statement have been written on multiple lines. For usage, you would have to put this on a single line.

The Day name is accessed from the array using the value returned by getDay() as index.

The code above prints: :Monday 29th August 2011

Format #6: Hours:Minutes (Finding the time)

Hours and minutes are obtained using getHours() and getMinutes() methods of the date object. The value returned by gethours() varies from 0 to 23.

<script type="text/javascript">
<!--
var d = new Date();
var curr_hour = d.getHours();
var curr_min = d.getMinutes();
document.write(curr_hour + " : " + curr_min);
//-->
</script>

Print: 9 : 58

There are two problem here. Firstly, if the hour or minutes is in single digits, JavaScript does not add any leading zeroes. Hence, 05:03 (AM) is printed as 5:3. Secondly, 12:00 AM becomes 0:00 (!). Let's see how to format time correctly.

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.

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: 10 : 0 AM

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: 10 : 00 AM

Format #9: Finding the number of seconds and milliseconds

getSeconds() and getMIlliseconds() return the seconds and milliseconds values.

<script type="text/javascript">
<!--
var d = new Date();
var curr_hour = d.getHours();
var curr_min = d.getMinutes();

var curr_sec = d.getSeconds();
var curr_msec = d.getMilliseconds();

document.write(curr_hour + ":" + curr_min + ":" 
+ curr_sec + ":" + curr_msec);
//-->
</script>

Prints: 10:1:38:530

Format #10: GMT Time

Each of the methods discussed so far calculates time on the client-side (browser). JavaScript also supplies us, similar methods for finding the GMT (called the Universal Coordinated Time or UTC).

  • getUTCDate(): Date
  • getUTCMonth(): Month
  • getUTCFullYear(): Year (4 digit)
  • getUTCDay(): Day
  • getUTCHours(): Hours
  • getUTCMinutes(): Minutes
  • getUTCSeconds(): Seconds
  • getUTCMilliseconds(): Milliseconds

You can use these methods to find the GMT and format it based on scripts discussed before.

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值