IdentifiantMot de passe
Loading...
Mot de passe oublié ?Je m'inscris ! (gratuit)
Navigation

Inscrivez-vous gratuitement
pour pouvoir participer, suivre les réponses en temps réel, voter pour les messages, poser vos propres questions et recevoir la newsletter

Contribuez Discussion :

Formatage de date


Sujet :

Contribuez

  1. #1
    Rédacteur

    Avatar de Bovino
    Homme Profil pro
    Développeur Web
    Inscrit en
    Juin 2008
    Messages
    23 647
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 53
    Localisation : France, Gironde (Aquitaine)

    Informations professionnelles :
    Activité : Développeur Web
    Secteur : High Tech - Éditeur de logiciels

    Informations forums :
    Inscription : Juin 2008
    Messages : 23 647
    Points : 91 220
    Points
    91 220
    Billets dans le blog
    20
    Par défaut Formatage de date


    Suite à une récente discussion sur le forum : formatage de date, j'ai créé une petite fonction de formatage.
    La chaine retournée est par défaut du type "jj/mm/aaaa", mais il est possible de passer une chaine à la fonction pour préciser le format souhaité.
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    /*
     * 	Formatage utilisé :
     * 		j : jour du mois
     * 		m : mois
     * 		a : année
     * 		h : heure
     * 		i : minutes
     * 		s : secondes
     */
    Date.prototype.format = function(){
    	this._nowFormat = arguments[0] || 'jj/mm/aaaa';
    	this._toLen2 = function(_nowStr){
    		_nowStr = _nowStr.toString();
    		return ('0'+_nowStr).substr(-2,2);
    	};
    	this._nowFormat = this._nowFormat.replace(/j+/, this._toLen2(this.getDate()));
    	this._nowFormat = this._nowFormat.replace(/m+/, this._toLen2(this.getMonth()+1));
    	this._nowFormat = this._nowFormat.replace(/a+/, this.getFullYear());
    	this._nowFormat = this._nowFormat.replace(/h+/, this._toLen2(this.getHours()));
    	this._nowFormat = this._nowFormat.replace(/i+/, this._toLen2(this.getMinutes()));
    	this._nowFormat = this._nowFormat.replace(/s+/, this._toLen2(this.getSeconds()));
    	return this._nowFormat;
    };
    L'utilisation est relativement simple, il suffit d'appeler la méthode format() à un objet Date :
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    var now = new Date();
    alert(now.format());
    Page de test : http://dmouronval.developpez.com/format-date/
    Pas de question technique par MP !
    Tout le monde peut participer à developpez.com, vous avez une idée, contactez-moi !
    Mes formations video2brain : La formation complète sur JavaScriptJavaScript et le DOM par la pratiquePHP 5 et MySQL : les fondamentaux
    Mon livre sur jQuery
    Module Firefox / Chrome d'intégration de JSFiddle et CodePen sur le forum

  2. #2
    Rédacteur

    Avatar de danielhagnoul
    Homme Profil pro
    Étudiant perpétuel
    Inscrit en
    Février 2009
    Messages
    6 389
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 73
    Localisation : Belgique

    Informations professionnelles :
    Activité : Étudiant perpétuel
    Secteur : Enseignement

    Informations forums :
    Inscription : Février 2009
    Messages : 6 389
    Points : 22 933
    Points
    22 933
    Billets dans le blog
    125
    Par défaut
    Bonjour

    Comme je ne manipule plus que des dates au format ISO long, version US (motif, voir : http://www.developpez.net/forums/d97...e-navigateurs/), j'ai créé une version à cet usage exclusif.

    Mes premiers tests donnent des résultats corrects.

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    /*
     * Date ISO format long, version US	
     */
    Date.prototype.formatISO = function(){
    	this._nowFormat = 'aaaa-mm-jjThh:ii:ss.000Szz:00';
    	this._toLen2 = function(_nowStr){
    		_nowStr = _nowStr.toString();
    		return ('0'+_nowStr).substr(-2,2);
    	};
    	this._nowFormat = this._nowFormat.replace(/j+/, this._toLen2(this.getDate()));
    	this._nowFormat = this._nowFormat.replace(/m+/, this._toLen2(this.getMonth()+1));
    	this._nowFormat = this._nowFormat.replace(/a+/, this.getFullYear());
    	this._nowFormat = this._nowFormat.replace(/h+/, this._toLen2(this.getHours()));
    	this._nowFormat = this._nowFormat.replace(/i+/, this._toLen2(this.getMinutes()));
    	this._nowFormat = this._nowFormat.replace(/s+/, this._toLen2(this.getSeconds()));
    	this._nowFormat = this._nowFormat.replace(/S+/, (this.getTimezoneOffset() < 0) ? ("+") : ("-"));
    	this._nowFormat = this._nowFormat.replace(/z+/, this._toLen2(Math.abs(this.getTimezoneOffset()/60)));
    	return this._nowFormat;
    };
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    console.log(new Date().formatISO());
     
    /*
     * 1977-04-22T01:00:00-05:00
     * 1977-04-22T08:00:00.000+02:00 En France, heure d'été.
     * Test OK sous C, F et IE dernières versions.
     */
    console.log(new Date("1977-04-22T01:00:00.000-05:00").formatISO());
     
    /*
     * 1977-01-22T01:00:00-05:00
     * 1977-01-22T07:00:00.000+01:00 En France, heure d'hiver.
     * Test OK sous C, F et IE dernières versions.
     */
    console.log(new Date("1977-01-22T01:00:00.000-05:00").formatISO());

    Blog

    Sans l'analyse et la conception, la programmation est l'art d'ajouter des bogues à un fichier texte vide.
    (Louis Srygley : Without requirements or design, programming is the art of adding bugs to an empty text file.)

  3. #3
    Expert confirmé
    Avatar de RomainVALERI
    Homme Profil pro
    POOête
    Inscrit en
    Avril 2008
    Messages
    2 652
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 47
    Localisation : France, Meurthe et Moselle (Lorraine)

    Informations professionnelles :
    Activité : POOête

    Informations forums :
    Inscription : Avril 2008
    Messages : 2 652
    Points : 4 164
    Points
    4 164
    Par défaut
    Citation Envoyé par danielhagnoul Voir le message
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    console.log(new Date().formatISO());
     
    /*
     * 1977-04-22T01:00:00-05:00
     * 1977-04-22T08:00:00.000+02:00 En France, heure d'été.
     * Test OK sous C, F et IE dernières versions.
     */
    Quand tu as exécuté la fonction j'avais un an
    (ou bien tu as fait des expériences mystiques avec ton horloge système... ? )

    En tout cas merci pour tes tests je n'avais pas encore lu

    ...pour les linguistes et les curieux >>> générateur de phrases aléatoires

    __________________

  4. #4
    Rédacteur

    Avatar de danielhagnoul
    Homme Profil pro
    Étudiant perpétuel
    Inscrit en
    Février 2009
    Messages
    6 389
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 73
    Localisation : Belgique

    Informations professionnelles :
    Activité : Étudiant perpétuel
    Secteur : Enseignement

    Informations forums :
    Inscription : Février 2009
    Messages : 6 389
    Points : 22 933
    Points
    22 933
    Billets dans le blog
    125
    Par défaut
    Bonjour Romain

    Comme d'habitude, format ISO ou pas, on peut créer une nouvelle date au choix (et avec le format ISO dans le fuseau horaire de son choix) et la méthode formatISO() donne l'équivalent local, au format ISO, en tenant compte de l'heure d'été si elle s'applique.

    // 1er janvier de l'an 1000 à 1h00 et 30s dans le fuseau horaire -5h par rapport à GMT
    var dAilleurs = new Date("1000-01-01T01:00:30.000-05:00");
    
    // la même heure au format texte US dans le fuseau horaire France
    // Wed Jan 01 1000 07:00:30 GMT+0100
    console.log(dAilleurs.toString());
    
    // le même instant, dans le fuseau horaire France au format ISO
    // 1000-01-01T07:00:30.000+01:00
    console.log(dAilleurs.formatISO());
    
    // en poussant le jeu inutilement, juste pour vérifier qu'il redonne bien la même date
    var dIci = new Date(dAilleurs.formatISO());
    
    // au format Locale, dans le fuseau horaire France
    // mercredi 1 janvier 1000 07:00:30
    console.log(dIci.toLocaleString());

    Blog

    Sans l'analyse et la conception, la programmation est l'art d'ajouter des bogues à un fichier texte vide.
    (Louis Srygley : Without requirements or design, programming is the art of adding bugs to an empty text file.)

  5. #5
    Expert confirmé
    Avatar de RomainVALERI
    Homme Profil pro
    POOête
    Inscrit en
    Avril 2008
    Messages
    2 652
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 47
    Localisation : France, Meurthe et Moselle (Lorraine)

    Informations professionnelles :
    Activité : POOête

    Informations forums :
    Inscription : Avril 2008
    Messages : 2 652
    Points : 4 164
    Points
    4 164
    Par défaut
    Citation Envoyé par danielhagnoul Voir le message
    Bonjour Romain

    Comme d'habitude, format ISO ou pas, on peut créer une nouvelle date au choix (et avec le format ISO dans le fuseau horaire de son choix) et la méthode formatISO() donne l'équivalent local, au format ISO, en tenant compte de l'heure d'été si elle s'applique.
    Ben oui ^^ mais là tu as appelé .formatISO sur new Date()... pas sur une date construite artificiellement dans le passé à partir d'une String donnée... ^^

    Non ? Qu'est-ce que j'ai raté ?

    ...pour les linguistes et les curieux >>> générateur de phrases aléatoires

    __________________

  6. #6
    Rédacteur

    Avatar de danielhagnoul
    Homme Profil pro
    Étudiant perpétuel
    Inscrit en
    Février 2009
    Messages
    6 389
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 73
    Localisation : Belgique

    Informations professionnelles :
    Activité : Étudiant perpétuel
    Secteur : Enseignement

    Informations forums :
    Inscription : Février 2009
    Messages : 6 389
    Points : 22 933
    Points
    22 933
    Billets dans le blog
    125
    Par défaut
    Citation Envoyé par RomainVALERI Voir le message
    Ben oui ^^ mais là tu as appelé .formatISO sur new Date()... pas sur une date construite artificiellement dans le passé à partir d'une String donnée... ^^

    Non ? Qu'est-ce que j'ai raté ?


    console.log(new Date("1977-04-22T01:00:00.000-05:00").formatISO());
    
    // la date dépassée et dans un autre fuseau horaire
    new Date("1977-04-22T01:00:00.000-05:00")
    
    // je construis la date et je la sors au format ISO
    // au lieu de .toString() par exemple
    new Date("1977-04-22T01:00:00.000-05:00").formatISO()
    Je te conseille de faire quelques tests, tu comprendras mieux.

    Blog

    Sans l'analyse et la conception, la programmation est l'art d'ajouter des bogues à un fichier texte vide.
    (Louis Srygley : Without requirements or design, programming is the art of adding bugs to an empty text file.)

  7. #7
    Expert confirmé
    Avatar de RomainVALERI
    Homme Profil pro
    POOête
    Inscrit en
    Avril 2008
    Messages
    2 652
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 47
    Localisation : France, Meurthe et Moselle (Lorraine)

    Informations professionnelles :
    Activité : POOête

    Informations forums :
    Inscription : Avril 2008
    Messages : 2 652
    Points : 4 164
    Points
    4 164
    Par défaut
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    console.log(new Date().formatISO());
     
    /*
     * 1977-04-22T01:00:00-05:00
     * 1977-04-22T08:00:00.000+02:00 En France, heure d'été.
     * Test OK sous C, F et IE dernières versions.
     */
    console.log(new Date("1977-04-22T01:00:00.000-05:00").formatISO());
    Dans l'extrait ci-dessus, tiré de ton post, les commentaires exprimant la "sortie console" sont placés en-dessous de cette ligne, alors qu'ils sont en réalité logiquement liés à celle-ci. ^^
    D'où ma confusion, j'ai du lire trop vite

    ...mais de là à penser que je suis incapable d'utiliser le constructeur de Dates, quand même... ! ()

    ...pour les linguistes et les curieux >>> générateur de phrases aléatoires

    __________________

  8. #8
    Rédacteur

    Avatar de danielhagnoul
    Homme Profil pro
    Étudiant perpétuel
    Inscrit en
    Février 2009
    Messages
    6 389
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 73
    Localisation : Belgique

    Informations professionnelles :
    Activité : Étudiant perpétuel
    Secteur : Enseignement

    Informations forums :
    Inscription : Février 2009
    Messages : 6 389
    Points : 22 933
    Points
    22 933
    Billets dans le blog
    125
    Par défaut
    Au dessus ou en dessous de la ligne de code, le commentaire se rapporte toujours à la ligne de code.

    Bref, c'est ma faute !

    Blog

    Sans l'analyse et la conception, la programmation est l'art d'ajouter des bogues à un fichier texte vide.
    (Louis Srygley : Without requirements or design, programming is the art of adding bugs to an empty text file.)

  9. #9
    Expert éminent
    Avatar de sekaijin
    Homme Profil pro
    Urbaniste
    Inscrit en
    Juillet 2004
    Messages
    4 205
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 60
    Localisation : France, Yvelines (Île de France)

    Informations professionnelles :
    Activité : Urbaniste
    Secteur : Santé

    Informations forums :
    Inscription : Juillet 2004
    Messages : 4 205
    Points : 9 127
    Points
    9 127
    Par défaut
    j'ai aussi en mon temps écrit un ensemble de méthodes sur les Dates.

    vous pouvez utiliser Ext-Core qui est une lib qui ser de base à Ext-JS.

    on y trouve des élément comme le formatage des dates. mais aussi pas mal d'utilitaires.
    pour la partie Date qui nous intéresse ici le formatage se fait selon une syntaxe semblable à celle de php
    Citation Envoyé par ext-js date class doc
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    77
    78
    /**
     * @class Ext.Date
     * A set of useful static methods to deal with date
     * Note that if Ext.Date is required and loaded, it will copy all methods / properties to
     * this object for convenience
     *
     * The date parsing and formatting syntax contains a subset of
     * <a href="http://www.php.net/date">PHP's date() function</a>, and the formats that are
     * supported will provide results equivalent to their PHP versions.
     *
     * The following is a list of all currently supported formats:
     * <pre class="">
    Format  Description                                                               Example returned values
    ------  -----------------------------------------------------------------------   -----------------------
      d     Day of the month, 2 digits with leading zeros                             01 to 31
      D     A short textual representation of the day of the week                     Mon to Sun
      j     Day of the month without leading zeros                                    1 to 31
      l     A full textual representation of the day of the week                      Sunday to Saturday
      N     ISO-8601 numeric representation of the day of the week                    1 (for Monday) through 7 (for Sunday)
      S     English ordinal suffix for the day of the month, 2 characters             st, nd, rd or th. Works well with j
      w     Numeric representation of the day of the week                             0 (for Sunday) to 6 (for Saturday)
      z     The day of the year (starting from 0)                                     0 to 364 (365 in leap years)
      W     ISO-8601 week number of year, weeks starting on Monday                    01 to 53
      F     A full textual representation of a month, such as January or March        January to December
      m     Numeric representation of a month, with leading zeros                     01 to 12
      M     A short textual representation of a month                                 Jan to Dec
      n     Numeric representation of a month, without leading zeros                  1 to 12
      t     Number of days in the given month                                         28 to 31
      L     Whether it's a leap year                                                  1 if it is a leap year, 0 otherwise.
      o     ISO-8601 year number (identical to (Y), but if the ISO week number (W)    Examples: 1998 or 2004
            belongs to the previous or next year, that year is used instead)
      Y     A full numeric representation of a year, 4 digits                         Examples: 1999 or 2003
      y     A two digit representation of a year                                      Examples: 99 or 03
      a     Lowercase Ante meridiem and Post meridiem                                 am or pm
      A     Uppercase Ante meridiem and Post meridiem                                 AM or PM
      g     12-hour format of an hour without leading zeros                           1 to 12
      G     24-hour format of an hour without leading zeros                           0 to 23
      h     12-hour format of an hour with leading zeros                              01 to 12
      H     24-hour format of an hour with leading zeros                              00 to 23
      i     Minutes, with leading zeros                                               00 to 59
      s     Seconds, with leading zeros                                               00 to 59
      u     Decimal fraction of a second                                              Examples:
            (minimum 1 digit, arbitrary number of digits allowed)                     001 (i.e. 0.001s) or
                                                                                      100 (i.e. 0.100s) or
                                                                                      999 (i.e. 0.999s) or
                                                                                      999876543210 (i.e. 0.999876543210s)
      O     Difference to Greenwich time (GMT) in hours and minutes                   Example: +1030
      P     Difference to Greenwich time (GMT) with colon between hours and minutes   Example: -08:00
      T     Timezone abbreviation of the machine running the code                     Examples: EST, MDT, PDT ...
      Z     Timezone offset in seconds (negative if west of UTC, positive if east)    -43200 to 50400
      c     ISO 8601 date
            Notes:                                                                    Examples:
            1) If unspecified, the month / day defaults to the current month / day,   1991 or
               the time defaults to midnight, while the timezone defaults to the      1992-10 or
               browser's timezone. If a time is specified, it must include both hours 1993-09-20 or
               and minutes. The "T" delimiter, seconds, milliseconds and timezone     1994-08-19T16:20+01:00 or
               are optional.                                                          1995-07-18T17:21:28-02:00 or
            2) The decimal fraction of a second, if specified, must contain at        1996-06-17T18:22:29.98765+03:00 or
               least 1 digit (there is no limit to the maximum number                 1997-05-16T19:23:30,12345-0400 or
               of digits allowed), and may be delimited by either a '.' or a ','      1998-04-15T20:24:31.2468Z or
            Refer to the examples on the right for the various levels of              1999-03-14T20:24:32Z or
            date-time granularity which are supported, or see                         2000-02-13T21:25:33
            <a href="http://www.w3.org/TR/NOTE-datetime" target="_blank">http://www.w3.org/TR/NOTE-datetime</a> for more info.                         2001-01-12 22:26:34
      U     Seconds since the Unix Epoch (January 1 1970 00:00:00 GMT)                1193432466 or -2138434463
      MS    Microsoft AJAX serialized dates                                           \/Date(1238606590509)\/ (i.e. UTC milliseconds since epoch) or
                                                                                      \/Date(1238606590509+0800)\/
    </pre>
     *
     * Example usage (note that you must escape format specifiers with '\\' to render them as character literals):
     * <pre><code>
    // Sample date:
    // 'Wed Jan 10 2007 15:05:01 GMT-0600 (Central Standard Time)'
     
    var dt = new Date('1/10/2007 03:05:01 PM GMT-0600');
    console.log(Ext.Date.format(dt, 'Y-m-d'));                          // 2007-01-10
    console.log(Ext.Date.format(dt, 'F j, Y, g:i a'));                  // January 10, 2007, 3:05 pm
    console.log(Ext.Date.format(dt, 'l, \\t\\he jS \\of F Y h:i:s A')); // Wednesday, the 10th of January 2007 03:05:01 PM
    </code></pre>
    plusieurs choses intéressante :
    le Support de Microsoft AJAX serialized dates
    le Support de l'internationalisation (45 langues supportés)
    la présence de Parser

    etc.

    Il est possible de n'utiliser que quelques éléments sans prendre toute la lib.
    mais il faut faire attention aux dépendances

    A+JYT

Discussions similaires

  1. [VBA-E] formatage cellule date
    Par jeff37 dans le forum Macros et VBA Excel
    Réponses: 5
    Dernier message: 17/05/2006, 22h31
  2. Formatage de date en diverses langues
    Par Caroline1 dans le forum Access
    Réponses: 6
    Dernier message: 26/04/2006, 14h47
  3. Formatage de date et 0
    Par christel1982 dans le forum ASP
    Réponses: 16
    Dernier message: 03/11/2005, 11h35
  4. [MSSQL][SQLDATE] Formatage de dates
    Par djskyz dans le forum Langage SQL
    Réponses: 6
    Dernier message: 15/09/2004, 10h36
  5. [tomcat] Formatage de date en FR
    Par PeteMitchell dans le forum Tomcat et TomEE
    Réponses: 3
    Dernier message: 10/05/2004, 11h41

Partager

Partager
  • Envoyer la discussion sur Viadeo
  • Envoyer la discussion sur Twitter
  • Envoyer la discussion sur Google
  • Envoyer la discussion sur Facebook
  • Envoyer la discussion sur Digg
  • Envoyer la discussion sur Delicious
  • Envoyer la discussion sur MySpace
  • Envoyer la discussion sur Yahoo