Thursday, January 26, 2012

Javascript Date formatting Techniques

Format Date and time :
We will be using following three methods:

getDate(): Returns the date
getMonth(): Returns the month
getFullYear(): Returns the year


1. Date format like 21-January-2012)
The getMonth() function gives us the month in a numeric form. To convert this value into the month name, we will use an array. The array would contain all the 12 month names.

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);


2. Date Format like month/day/year

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)


3.Format like Wednesday 25th January 2012

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 + "
" + m_names[curr_month] + " " + curr_year);

4.Hours:Minutes

var d = new Date();
var curr_hour = d.getHours();
var curr_min = d.getMinutes();
document.write(curr_hour + " : " + curr_min);

5. Time with AM and PM
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);

6. Two digit minutes
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);

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

No comments: