Date Formatting in Javascript

Can we format date in javascript as per our requirement ? Yes, we can do this in few lines of code in javascript , Outputting a lot of dates to the browser, and want to format them nicely? The following code adds a customFormat() method to the Date class which allows you to have a Date object turn into a string formatted just the way you like. Simply include this small block of code (in a separate client-side library file, directly in your JS ) and all date objects will suddenly be able to cleanly format themselves. Click here to Download Demo .

Code :
  1. <!--Author : Mohammad Usman
  2.    Date   : 10/01/2011 -->
  3. <head><title>Date Formatting in Javascript</title>
  4. <script language="javascript">
  5. function datetestmethode(){
  6. Date.prototype.customFormat=function(formatString){
  7.    var YYYY,YY,MMMM,MMM,MM,M,DDDD,DDD,DD,D,hhh,hh,h,mm,m,ss,s,ampm,dMod,th;
  8.    YY = ((YYYY=this.getFullYear())+"").substr(2,2);
  9.    MM = (M=this.getMonth()+1)<10?('0'+M):M;
  10.   MMM = (MMMM=["January","February","March","April","May","June","July","August","September","October","November","December"][M-1]).substr(0,3);
  11.   DD = (D=this.getDate())<10?('0'+D):D;
  12.   DDD = (DDDD=["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"][this.getDay()]).substr(0,3);
  13.   th=(D>=10&&D<=20)?'th':((dMod=D%10)==1)?'st':(dMod==2)?'nd':(dMod==3)?'rd':'th';
  14.    formatString = formatString.replace("#YYYY#",YYYY).replace("#YY#",YY).replace("#MMMM#",MMMM).replace("#MMM#",MMM).replace("#MM#",MM).replace("#M#",M).replace("#DDDD#",DDDD).replace("#DDD#",DDD).replace("#DD#",DD).replace("#D#",D).replace("#th#",th);
  15.    h=(hhh=this.getHours());
  16.    if (h==0) h=24;
  17.    if (h>12) h-=12;
  18.    hh = h<10?('0'+h):h;
  19.   ampm=hhh<12?'am':'pm';
  20.   mm=(m=this.getMinutes())<10?('0'+m):m;
  21.   ss=(s=this.getSeconds())<10?('0'+s):s;
  22.   return formatString.replace("#hhh#",hhh).replace("#hh#",hh).replace("#h#",h).replace("#mm#",mm).replace("#m#",m).replace("#ss#",ss).replace("#s#",s).replace("#ampm#",ampm);
  23. }
  24. var now=new Date();
  25. alert("Today is "+now.customFormat('#DDDD#, #MMMM# #D##th#,#YYYY#')+"\nThe time is "+now.customFormat('#h#:#mm##ampm#')+".");
  26. }
  27. </head>
  28. <input type="button" value="Click Me to Format Date" onclick="datetestmethode();"/>
  29. </html>


No comments:

Post a Comment

Comment On Facebook