Précédent   Forum des professionnels en informatique > Webmasters - Développement Web > Contribuez
Contribuez Proposez vos articles, cours, tutoriels, questions/réponses pour les FAQ, sources et autres ressources pour la rubrique Web ainsi que ses sous-rubriques.
Partagez cette discussion sur d'autres réseaux sociaux : Viadeo Twitter Google Facebook Digg Delicious MySpace Yahoo
Réponse Proposer ce sujet en actualité
 
Outils de la discussion
Publicité
'
Vieux 18/04/2011, 09h48   #1
Responsable Développement Web

 
Avatar de Bovino
 
Homme Didier Mouronval
Développeur Web
Inscription : juin 2008
Messages : 13 806
Détails du profil
Informations personnelles :
Nom : Homme Didier Mouronval
Âge : 41
Localisation : France, Gironde (Aquitaine)

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

Informations forums :
Inscription : juin 2008
Messages : 13 806
Points : 35 803
Points : 35 803
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 :
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 :
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 !
Vous possédez un blog et aimeriez diffuser vos billets sur le forum, 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
Bovino est déconnecté   Envoyer un message privé Réponse avec citation 20
Vieux 07/05/2011, 10h47   #2
Rédacteur
 
Avatar de danielhagnoul
 
Homme Daniel Hagnoul
Étudiant perpétuel
Inscription : février 2009
Messages : 3 221
Détails du profil
Informations personnelles :
Nom : Homme Daniel Hagnoul
Âge : 61
Localisation : Belgique

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

Informations forums :
Inscription : février 2009
Messages : 3 221
Points : 6 767
Points : 6 767
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 :
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 :
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());
__________________

FAQ jQuery

Mon cahier d’exercices sur jQuery & Co

Si un message vous a aidé ou vous semble pertinent, votez pour lui !
danielhagnoul est déconnecté   Envoyer un message privé Réponse avec citation 00
Vieux 10/05/2011, 10h25   #3
Expert Confirmé Sénior
 
Avatar de RomainVALERI
 
Homme Romain VALERI
POOête
Inscription : avril 2008
Messages : 2 572
Détails du profil
Informations personnelles :
Nom : Homme Romain VALERI
Âge : 35
Localisation : France, Meurthe et Moselle (Lorraine)

Informations professionnelles :
Activité : POOête

Informations forums :
Inscription : avril 2008
Messages : 2 572
Points : 4 074
Points : 4 074
Citation:
Envoyé par danielhagnoul Voir le message
Code :
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

__________________
RomainVALERI est déconnecté   Envoyer un message privé Réponse avec citation 00
Vieux 10/05/2011, 11h11   #4
Rédacteur
 
Avatar de danielhagnoul
 
Homme Daniel Hagnoul
Étudiant perpétuel
Inscription : février 2009
Messages : 3 221
Détails du profil
Informations personnelles :
Nom : Homme Daniel Hagnoul
Âge : 61
Localisation : Belgique

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

Informations forums :
Inscription : février 2009
Messages : 3 221
Points : 6 767
Points : 6 767
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());
__________________

FAQ jQuery

Mon cahier d’exercices sur jQuery & Co

Si un message vous a aidé ou vous semble pertinent, votez pour lui !
danielhagnoul est déconnecté   Envoyer un message privé Réponse avec citation 00
Vieux 10/05/2011, 11h28   #5
Expert Confirmé Sénior
 
Avatar de RomainVALERI
 
Homme Romain VALERI
POOête
Inscription : avril 2008
Messages : 2 572
Détails du profil
Informations personnelles :
Nom : Homme Romain VALERI
Âge : 35
Localisation : France, Meurthe et Moselle (Lorraine)

Informations professionnelles :
Activité : POOête

Informations forums :
Inscription : avril 2008
Messages : 2 572
Points : 4 074
Points : 4 074
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

__________________
RomainVALERI est déconnecté   Envoyer un message privé Réponse avec citation 00
Vieux 10/05/2011, 19h53   #6
Rédacteur
 
Avatar de danielhagnoul
 
Homme Daniel Hagnoul
Étudiant perpétuel
Inscription : février 2009
Messages : 3 221
Détails du profil
Informations personnelles :
Nom : Homme Daniel Hagnoul
Âge : 61
Localisation : Belgique

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

Informations forums :
Inscription : février 2009
Messages : 3 221
Points : 6 767
Points : 6 767
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.
__________________

FAQ jQuery

Mon cahier d’exercices sur jQuery & Co

Si un message vous a aidé ou vous semble pertinent, votez pour lui !
danielhagnoul est déconnecté   Envoyer un message privé Réponse avec citation 00
Vieux 10/05/2011, 20h03   #7
Expert Confirmé Sénior
 
Avatar de RomainVALERI
 
Homme Romain VALERI
POOête
Inscription : avril 2008
Messages : 2 572
Détails du profil
Informations personnelles :
Nom : Homme Romain VALERI
Âge : 35
Localisation : France, Meurthe et Moselle (Lorraine)

Informations professionnelles :
Activité : POOête

Informations forums :
Inscription : avril 2008
Messages : 2 572
Points : 4 074
Points : 4 074
Code :
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

__________________
RomainVALERI est déconnecté   Envoyer un message privé Réponse avec citation 00
Vieux 10/05/2011, 22h18   #8
Rédacteur
 
Avatar de danielhagnoul
 
Homme Daniel Hagnoul
Étudiant perpétuel
Inscription : février 2009
Messages : 3 221
Détails du profil
Informations personnelles :
Nom : Homme Daniel Hagnoul
Âge : 61
Localisation : Belgique

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

Informations forums :
Inscription : février 2009
Messages : 3 221
Points : 6 767
Points : 6 767
Au dessus ou en dessous de la ligne de code, le commentaire se rapporte toujours à la ligne de code.

Bref, c'est ma faute !
__________________

FAQ jQuery

Mon cahier d’exercices sur jQuery & Co

Si un message vous a aidé ou vous semble pertinent, votez pour lui !
danielhagnoul est déconnecté   Envoyer un message privé Réponse avec citation 00
Vieux 14/05/2011, 14h12   #9
Expert Confirmé
 
Avatar de sekaijin
 
Femme
Urbaniste
Inscription : juillet 2004
Messages : 1 419
Détails du profil
Informations personnelles :
Sexe : Femme
Âge : 48
Localisation : France, Yvelines (Île de France)

Informations professionnelles :
Activité : Urbaniste
Secteur : Santé

Informations forums :
Inscription : juillet 2004
Messages : 1 419
Points : 2 806
Points : 2 806
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 :
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
sekaijin est déconnecté   Envoyer un message privé Réponse avec citation 00
Réponse Proposer ce sujet en actualité
Outils de la discussion



Fuseau horaire GMT +2. Il est actuellement 04h55.


 
 
 
 
Partenaires

Hébergement Web