Javascript: formatting date like PHP

- tags: javascript, programming, web - 3 comments

Come di sicuro saprete, Javascript, a differenza di altri linguaggi di programmazione come il PHP, è sprovvisto di una propria funzione date con cui poter formattare le date. Ecco dunque un’implementazione di questa utilissima funzione:

/*
    Title ----- formatdate.js
    Website --- http://hackyourmind.org/

    Copyright (C) 2012 Giacomo Trudu aka `Wicker25` - wicker25[at]gmail[dot]com

    This script is free software: you can redistribute it and/or modify
    it under the terms of the GNU Lesser General Public License as published by
    the Free Software Foundation version 3 of the License.

    This script is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
    GNU Lesser General Public License for more details.

    You should have received a copy of the GNU Lesser General Public License
    along with this script. If not, see <http://www.gnu.org/licenses/>.

   = Version 2.0 =
     + improved performance
*/

/** Formatting date like php  **/
var formatDate = function ( format, time, r ) {

   r = ( typeof r != 'undefined' && r );

   // Build the Date object
   var date = ( typeof time != 'undefined' ) ? ( time instanceof Date ? time : new Date( time * 1000 ) ) : new Date;

   // Number of seconds since the beginning of this year
   var year_seconds = ( date - new Date( date.getFullYear(), 0, 1 ) ) / 1000;

   // Retrieve the date informations
   var meta = String( date ).match( /^.*?([A-Z]{1,4})([\-+]\d{4}) \(([A-Z]+)\).*$/ );

   date = {

      d : date.getDate(),
      D : date.getDay(),
      m : date.getMonth(),
      y : date.getFullYear(),
      l : ( new Date( date.getFullYear(), 1, 29 ).getMonth() === 1 | 0 ),
      h : date.getHours(),
      M : date.getMinutes(),
      s : date.getSeconds(),
      u : date.getMilliseconds(),
      t : date.getTime(),
      z : date.getTimezoneOffset()
   };

   // Stringa della data formattata
   var timestr = '';

   // Riempie di zeri le cifre alla sinistra di un numero
   var pad = function ( value, len ) {

      return ( '000000000' + String( value ) ).slice( -len );
   };

   // Define the format characters
   var fmt_characters = {

      d : function () { return pad( date.d, 2 ); },
      D : function () { return [ 'Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat' ][ date.D ]; },
      j : function () { return date.d; },
      l : function () { return [ 'Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday' ][ date.D ]; },
      N : function () { return date.D + 1; },
      S : function () { return [ 'th', 'st', 'nd', 'rd' ][ date.d % 10 > 3 ? 0 : ( date.d < 10 || date.d > 20 ) * date.d % 10 ]; },
      w : function () { return date.D; },
      z : function () { return Math.ceil( year_seconds / 86400 ); },
      W : function () { return Math.ceil( year_seconds / 604800 ); },
      F : function () { return [ 'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec' ][ date.m ]; },
      m : function () { return pad( date.m + 1, 2 ); },
      M : function () { return [ 'January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December' ][ date.m ]; },
      n : function () { return date.m + 1; },
      t : function () { return [31, (date.l ? 29 : 28), 31, 30, 31, 30, 31, 31, 30, 31, 30, 31][ date.m ]; },
      L : function () { return date.l; },
      Y : function () { return date.y; },
      y : function () { return String( date.y ).slice( -2 ); },
      a : function () { return ( date.h < 12 ? 'am' : 'pm' ); },
      A : function () { return ( date.h < 12 ? 'AM' : 'PM' ); },
      g : function () { return date.h % 12 || 12; },
      G : function () { return date.h; },
      h : function () { return pad( date.h % 12 || 12, 2 ); },
      H : function () { return pad( date.h, 2 ); },
      i : function () { return pad( date.M, 2 ); },
      s : function () { return pad( date.s, 2 ); },
      u : function () { return date.u * 1000; },
      I : function () { return ( date.m > 2 && date.m < 10 || ( date.m == 2 && date.D - date.d >= 8 - 1 ) ); },
      O : function () { return meta[2]; },
      P : function () { return meta[2].slice( 0, -2 ) + ':' + meta[2].slice( -2 ); },
      T : function () { return meta[3]; },
      Z : function () { return -date.z * 60; },
      c : function () { return ( !r ? formatDate( 'Y-m-d\\TH:i:sP', time, true ) : null ); },
      r : function () { return ( !r ? formatDate( 'D, d M Y H:i:s O', time, true ) : null ); },
      U : function () { return Math.floor( date.t / 1000 ); }
   };

   // Split the format string into tokens
   var tokens = format.match( /(\\.|.)/gi );

   // Make the time string
   for ( var i = 0; i < tokens.length; i++ )
      timestr += ( tokens[i] in fmt_characters ? fmt_characters[ tokens[i] ]() : ( tokens[i].length == 1 ? tokens[i] : tokens[i][1] ) );

   return timestr;
};

[Scarica il sorgente]

Di seguito qualche esempio di utilizzo:

formatDate( 'j, n, Y' ); // => '10, 3, 2001'
formatDate( 'F j, Y, g:i a' ); // => 'March 10, 2001, 5:16 pm'
formatDate( 'd/m/Y', 1230000000 ); // => '23/12/2008'
formatDate( 'H:i', new Date() ); // => '19:52'
formatDate( 'c' ); // => '2012-04-20T19:12:35+02:00'
formatDate( '\\i\\t \\i\\s \\t\\h\\e jS \\d\\a\\y.' ); // => 'it is the 20th day.'

La si può utilizzare anche come metodo del tipo Date, in questo modo:

Date.prototype.format = function ( format ) {
    return formatDate( format, this );
};

var timestr = new Date().format( 'd/m/Y' );

Alla prossima.. ;)

Did you find this article helpful?

3 comments

  1. Ciao, ho apprezzato e usato il tuo formattatore. Ho aggiunto una semplice gestione delle altre lingue. Ti passo in codice, se interessa.

    Date.prototype.format = function ( format, r, locale ) {
    // by Giacomo Trudu
       r = ( typeof r != 'undefined' &amp;&amp; r );
    
       var time = this;
    
       // Build the Date object
       var date = ( typeof time != 'undefined' ) ? ( time instanceof Date ? time : new Date( time * 1000 ) ) : new Date;
    
       // Number of seconds since the beginning of this year
       var year_seconds = ( date - new Date( date.getFullYear(), 0, 1 ) ) / 1000;
    
       // Retrieve the date informations
       var meta = String( date ).match( /^.*?([A-Z]{1,4})([\-+]\d{4}) \(([A-Z]+)\).*$/ );
    
       date = {
    
          d : date.getDate(),
          D : date.getDay(),
          m : date.getMonth(),
          y : date.getFullYear(),
          l : ( new Date( date.getFullYear(), 1, 29 ).getMonth() === 1 | 0 ),
          h : date.getHours(),
          M : date.getMinutes(),
          s : date.getSeconds(),
          u : date.getMilliseconds(),
          t : date.getTime(),
          z : date.getTimezoneOffset()
       };
    
       // Stringa della data formattata
       var timestr = '';
    
       // Riempie di zeri le cifre alla sinistra di un numero
       var pad = function ( value, len ) {
    
          return ( '000000000' + String( value ) ).slice( -len );
       };
    
        if (!locale) locale = 'it';
        var locale_string = {
            it: {
                D:  [ 'Dom', 'Lun', 'Mar', 'Mer', 'Gio', 'Ven', 'Sab' ],
                l:  [ 'Domenica', 'Lunedì', 'Martedì', 'Mercoledì', 'Giovedì', 'Venerdì', 'Sabato' ],
                S:  [ '', '', '', '' ],
                F:  [ 'Gen', 'Feb', 'Mar', 'Apr', 'Mag', 'Giu', 'Lug', 'Ago', 'Set', 'Ott', 'Nov', 'Dic' ],
                M:  [ 'gennaio', 'febbraio', 'marzo', 'aprile', 'maggio', 'giugno', 'luglio', 'agosto', 'settembre', 'ottobre', 'novembre', 'dicembre' ]
            },
            en: {
                D:  [ 'Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat' ],
                l:  [ 'Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday' ],
                S:  [ 'th', 'st', 'nd', 'rd' ],
                F:  [ 'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec' ],
                M:  [ 'January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December' ]
            } 
        }
    
       // Define the format characters
       var fmt_characters = {
    
          d : function () { return pad( date.d, 2 ); },
          D : function () { return locale_string[locale].D[ date.D ]; },
          j : function () { return date.d; },
          l : function () { return locale_string[locale].l[ date.D ]; },
          N : function () { return date.D + 1; },
          S : function () { return locale_string[locale].S[ date.d % 10 &gt; 3 ? 0 : ( date.d  20 ) * date.d % 10 ]; },
          w : function () { return date.D; },
          z : function () { return Math.ceil( year_seconds / 86400 ); },
          W : function () { return Math.ceil( year_seconds / 604800 ); },
          F : function () { return locale_string[locale].F[ date.m ]; },
          m : function () { return pad( date.m + 1, 2 ); },
          M : function () { return locale_string[locale].M[ date.m ]; },
          n : function () { return date.m + 1; },
          t : function () { return [31, (date.l ? 29 : 28), 31, 30, 31, 30, 31, 31, 30, 31, 30, 31][ date.m ]; },
          L : function () { return date.l; },
          Y : function () { return date.y; },
          y : function () { return String( date.y ).slice( -2 ); },
          a : function () { return ( date.h  2 &amp;&amp; date.m = 8 - 1 ) ); },
          O : function () { return meta[2]; },
          P : function () { return meta[2].slice( 0, -2 ) + ':' + meta[2].slice( -2 ); },
          T : function () { return meta[3]; },
          Z : function () { return -date.z * 60; },
          c : function () { return ( !r ? formatDate( 'Y-m-d\\TH:i:sP', time, true ) : null ); },
          r : function () { return ( !r ? formatDate( 'D, d M Y H:i:s O', time, true ) : null ); },
          U : function () { return Math.floor( date.t / 1000 ); }
       };
    
       // Split the format string into tokens
       var tokens = format.match( /(\\.|.)/gi );
    
       // Make the time string
       for ( var i = 0; i 
    
    Silvio Sosio on Sat, 29 Mar 2014 @ 8:05 am user image
  2. Ciao Silvio,

    ti rigranzio, anche se purtroppo il tuo codice ha superato la lunghezza massima del messaggio ed è stato troncato. Potresti caricarlo su un servizio esterno come ad esempio http://pastebin.com/?

    Grazie,

    Giacomo

    admin on Sun, 30 Mar 2014 @ 10:33 am user image
  3. Sure: http://pastebin.com/7Dm70yQj

    Silvio Sosio on Sun, 30 Mar 2014 @ 10:42 am user image