Conversion des horodatages en heure locale avec date_l18n ()
-
-
Avez-vous défini votrefuseau horaire dans Paramètres-> Général?Have you set your timezone in Settings->General?
- 0
- 2013-04-05
- vancoder
-
Oui,à Los Angeles.Yes, to Los Angeles.
- 0
- 2013-04-05
- Andrew Bartel
-
6 réponses
- votes
-
- 2013-07-20
Je sais quej'aitroismois de retard,mais lafonction que vous vouleziciest
get_date_from_gmt()
.Lafonction accepte une date GMT/UTC auformat
Y-m-d H:i:s
commepremierparamètre,et leformat de date souhaité comme deuxièmeparamètre.Il convertira votre date dans lefuseau horaire localtel que défini sur l'écran Paramètres.Exemple d'utilisation:
echo get_date_from_gmt( date( 'Y-m-d H:i:s', $my_unix_timestamp ), 'F j, Y H:i:s' );
I know I'm three months late, but the function you want here is WordPress'
get_date_from_gmt()
.The function accepts a GMT/UTC date in
Y-m-d H:i:s
format as the first parameter, and your desired date format as the second parameter. It'll convert your date to the local timezone as set on the Settings screen.Example usage:
echo get_date_from_gmt( date( 'Y-m-d H:i:s', $my_unix_timestamp ), 'F j, Y H:i:s' );
-
Killermerci,j'ai vu cepopup dansmesnotificationstout à l'heure.Je l'ai changépour labonne réponse.Killer thanks, saw this popup in my notifications just now. I switched it to the correct answer.
- 2
- 2013-07-22
- Andrew Bartel
-
J'ai ajouté la configuration de la dateet de l'heure: `echoget_date_from_gmt (date ('Y-m-d H:i: s',$mon_horodatage),get_option ('date_format'). '-'.get_option ('time_format'));`I added the date and time configuration: `echo get_date_from_gmt ( date( 'Y-m-d H:i:s', $my_timestamp ), get_option('date_format') . ' - '. get_option('time_format') );`
- 1
- 2014-07-21
- Nabil Kadimi
-
@NabilKadimi c'est unexcellent ajout,maisilne traduittoujourspas la chaîne dans labonne langue.Voir [ma réponse] (https://wordpress.stackexchange.com/a/339190/122391)pour unefonction quiprenden compte lestrois de la langue configurée,dufuseau horaireet duformat de date.@NabilKadimi that's a great addition, but it still doesn't translate the string to the correct language. See [my answer](https://wordpress.stackexchange.com/a/339190/122391) for a function that takes into account all three of the configured language, timezone, and date format.
- 0
- 2019-05-30
- Flimm
-
- 2013-04-05
Depuis le codex :
current_time ('timestamp') doit être utilisé à laplace detime ()pour retourner l'heure locale dublog.Dans WordPress,letemps de PHP () reviendratoujours UTCet équivaut à appeler current_time ('timestamp',true).
Essayez ceci:
define( 'MY_TIMEZONE', (get_option( 'timezone_string' ) ? get_option( 'timezone_string' ) : date_default_timezone_get() ) ); date_default_timezone_set( MY_TIMEZONE ); echo date_i18n('F d, Y H:i', 1365194723);
Ceci définit la date PHPpar défaut sur l'optiontimezone_string de WP,si disponible,pour la durée du script.
From the codex:
current_time('timestamp') should be used in lieu of time() to return the blog's local time. In WordPress, PHP's time() will always return UTC and is the same as calling current_time('timestamp', true).
Try this:
define( 'MY_TIMEZONE', (get_option( 'timezone_string' ) ? get_option( 'timezone_string' ) : date_default_timezone_get() ) ); date_default_timezone_set( MY_TIMEZONE ); echo date_i18n('F d, Y H:i', 1365194723);
This sets the default PHP date to WP's timezone_string option, if available, for the duration of the script.
-
D'accord,mais quefaire sij'ai un horodatage arbitraire?Disons qu'il y a quelquesjours,commentpuis-je obtenir l'heure ajustéeplutôt que l'heure UTC?Right, but what if I have an arbitrary timestamp? Say from a couple days ago, how do I get the adjusted time rather than UTC time?
- 1
- 2013-04-05
- Andrew Bartel
-
`date_i18n ('F d,Y H:i',$ your_timestamp)`ne fonctionnepas?does `date_i18n('F d, Y H:i', $your_timestamp)` not work?
- 0
- 2013-04-05
- vancoder
-
Non,mêmeessayé sur uneinstallation WP vanilla avec 2012en exécutant simplement cette déclaration `echo date_i18n ('F d,YH:i',1365194723)`en haut deindex.php,quime donne l'heure UTCplutôt que la côte ouest des États-Unis.Nope, even tried it on a vanilla WP install with 2012 just running this `echo date_i18n('F d, Y H:i',1365194723)` statement at the top of index.php, that gives me UTC rather than US West Coast time.
- 0
- 2013-04-05
- Andrew Bartel
-
Vous avez raison,il semble que date_i18nestprincipalement destiné au _formatage_ local des dates,plutôt qu'à l'ajustement de la date.J'aimis àjourma réponse.You're right, it looks like date_i18n is mainly for local _formatting_ of dates, rather than date adjustment. I have updated my answer.
- 0
- 2013-04-05
- vancoder
-
Oui,j'espérais éviter d'avoir à régler lefuseau horairemanuellement,mais si c'est le seulmoyen,qu'ilen soit ainsi.Marqué comme répondu,mercipour l'aide.Yea, I was hoping to avoid having to set the timezone manually, but if that's the only way, so be it. Marked as answered, thanks for the help.
- 0
- 2013-04-05
- Andrew Bartel
-
WordPress appelle `date_default_timezone_set ('UTC');`,cela semble être unemauvaiseidée de remplacer celaen appelant vous-même `date_default_timezone_set`,car le codeet lesplugins WordPresspeuvent s'appuyer sur ce comportement.WordPress calls `date_default_timezone_set( 'UTC' );`, it seems like a bad idea to override this by calling `date_default_timezone_set` yourself, as WordPress code and plugins may be relying on that behaviour.
- 0
- 2019-05-30
- Flimm
-
- 2014-02-18
date_i18n($format, $timestamp)
en fonction desparamètres régionaux,maispas dufuseau horaire.get_date_from_gmt($datestring, $format)
formatsen fonction dufuseau horaire,maispas desparamètres régionaux. Pour obtenir lamiseen formeen fonction à lafois dufuseau horaire et desparamètres régionaux,je fais ce qui suit:function local_date_i18n($format, $timestamp) { $timezone_str = get_option('timezone_string') ?: 'UTC'; $timezone = new \DateTimeZone($timezone_str); // The date in the local timezone. $date = new \DateTime(null, $timezone); $date->setTimestamp($timestamp); $date_str = $date->format('Y-m-d H:i:s'); // Pretend the local date is UTC to get the timestamp // to pass to date_i18n(). $utc_timezone = new \DateTimeZone('UTC'); $utc_date = new \DateTime($date_str, $utc_timezone); $timestamp = $utc_date->getTimestamp(); return date_i18n($format, $timestamp, true); }
Exemple deprogramme:
$format = 'F d, Y H:i'; $timestamp = 1365186960; $local = local_date_i18n($format, $timestamp); $gmt = date_i18n($format, $timestamp); echo "Local: ", $local, " UTC: ", $gmt;
Sortiepour lefuseau horaire de Los Angeles:
Local: 05 avril 2013 11:36 UTC: 05 avril 2013 18:36
Références:
-
DateTimeZone
docs en php .net -
DateTime
docs en php .net,y comprissetTimestamp
,< a href="https://www.php.net/manual/en/datetime.gettimestamp.php" rel="nofollownoreferrer">getTimestamp
etformat
- Documentation de
date_i18n
date_i18n($format, $timestamp)
formats according to the locale, but not the timezone.get_date_from_gmt($datestring, $format)
formats according to the timezone, but not the locale. To get formatting according to both the timezone and the locale, I am doing the following:function local_date_i18n($format, $timestamp) { $timezone_str = get_option('timezone_string') ?: 'UTC'; $timezone = new \DateTimeZone($timezone_str); // The date in the local timezone. $date = new \DateTime(null, $timezone); $date->setTimestamp($timestamp); $date_str = $date->format('Y-m-d H:i:s'); // Pretend the local date is UTC to get the timestamp // to pass to date_i18n(). $utc_timezone = new \DateTimeZone('UTC'); $utc_date = new \DateTime($date_str, $utc_timezone); $timestamp = $utc_date->getTimestamp(); return date_i18n($format, $timestamp, true); }
Example program:
$format = 'F d, Y H:i'; $timestamp = 1365186960; $local = local_date_i18n($format, $timestamp); $gmt = date_i18n($format, $timestamp); echo "Local: ", $local, " UTC: ", $gmt;
Output for the timezone of Los Angeles:
Local: April 05, 2013 11:36 UTC: April 05, 2013 18:36
References:
DateTimeZone
docs in php.netDateTime
docs in php.net, includingsetTimestamp
,getTimestamp
andformat
- WordPress'
date_i18n
docs
-
- 2019-05-30
Conversion de l'UTCen chaîne dans lefuseau horaire,la langueet leformat dans les options de WordPress
J'ai créé unefonctionbien documentée qui convertit une chaîne date-heureen UTCen unejolie chaîne date-heure dans la langue,leformatet lefuseau horaire appropriés. N'hésitezpas à le copier.
Parexemple,passer
"2019-05-30 18:06:01"
(en UTC) renverrait"Maggio 30, 2019 10:06 am"
./** * Given a string with the date and time in UTC, returns a pretty string in the * configured language, format and timezone in WordPress' options. * * @param string $utc_date_and_time * e.g: "2019-05-30 18:06:01" * This argument must be in UTC. * @return string * e.g: "Maggio 30, 2019 10:06 am" * This returns a pretty datetime string in the correct language and * following the admin's settings. */ function pretty_utc_date( string $utc_date ): string { if (! preg_match( '/^\d\d\d\d-\d\d-\d\d \d\d:\d\d:\d\d$/', $utc_date ) ) { /* I have not tested other formats, so only this one allowed. */ throw new InvalidArgumentException( "Expected argument to be in YYYY-MM-DD hh:mm:ss format" ); } $date_in_local_timezone = get_date_from_gmt( $utc_date ); /* $date_in_local_timezone is now something like "2019-05-30 10:06:01" * in the timezone of get_option( 'timezone_string' ), configured in * WordPress' general settings in the backend user interface. */ /* Unfortunately, we can't just pass this to WordPress' date_i18n, as that * expects the second argument to be the number of seconds since 1/Jan/1970 * 00:00:00 in the timezone of get_option( 'timezone_string' ), which is not the * same as a UNIX epoch timestamp, which is the number of seconds since * 1/Jan/1970 00:00:00 GMT. */ $seconds_since_local_1_jan_1970 = (new DateTime( $date_in_local_timezone, new DateTimeZone( 'UTC' ) )) ->getTimestamp(); // e.g: 1559210761 /* Administrators can set a preferred date format and a preferred time * format in WordPress' general settings in the backend user interface, we * need to retrieve that. */ $settings_format = get_option( 'date_format' ) . ' '. get_option( 'time_format' ); // $settings_format is in this example "F j, Y g:i a" /* In this example, the installation of WordPress has been set to Italian, * and the final result is "Maggio 30, 2019 10:06 am" */ return date_i18n( $settings_format, $seconds_since_local_1_jan_1970 ); }
Références:
- Documents WordPress
get_date_from_gmt
-
DateTimeZone
docs en php .net -
DateTime
docs en php .net,y comprisgetTimestamp
- Documentation de
date_i18n
- Il convient de rappeler que WordPressexécute
date_default_timezone_set( 'UTC' );
quel que soit lefuseau horaire sélectionnépar l'administrateur dans l'interface utilisateur,gardez donc cela à l'esprit lors de la détermination du comportement desfonctions PHPintégrées . Consultez ladate_default_timezone_set
documentation dansphp.net.
Converting UTC to string in timezone, language and format in WordPress' options
I've created a well-document function that converts a date-time string in UTC to a pretty date-time string in the correct language, format and timezone. Feel free to copy it.
For example, passing in
"2019-05-30 18:06:01"
(in UTC) would return"Maggio 30, 2019 10:06 am"
./** * Given a string with the date and time in UTC, returns a pretty string in the * configured language, format and timezone in WordPress' options. * * @param string $utc_date_and_time * e.g: "2019-05-30 18:06:01" * This argument must be in UTC. * @return string * e.g: "Maggio 30, 2019 10:06 am" * This returns a pretty datetime string in the correct language and * following the admin's settings. */ function pretty_utc_date( string $utc_date ): string { if (! preg_match( '/^\d\d\d\d-\d\d-\d\d \d\d:\d\d:\d\d$/', $utc_date ) ) { /* I have not tested other formats, so only this one allowed. */ throw new InvalidArgumentException( "Expected argument to be in YYYY-MM-DD hh:mm:ss format" ); } $date_in_local_timezone = get_date_from_gmt( $utc_date ); /* $date_in_local_timezone is now something like "2019-05-30 10:06:01" * in the timezone of get_option( 'timezone_string' ), configured in * WordPress' general settings in the backend user interface. */ /* Unfortunately, we can't just pass this to WordPress' date_i18n, as that * expects the second argument to be the number of seconds since 1/Jan/1970 * 00:00:00 in the timezone of get_option( 'timezone_string' ), which is not the * same as a UNIX epoch timestamp, which is the number of seconds since * 1/Jan/1970 00:00:00 GMT. */ $seconds_since_local_1_jan_1970 = (new DateTime( $date_in_local_timezone, new DateTimeZone( 'UTC' ) )) ->getTimestamp(); // e.g: 1559210761 /* Administrators can set a preferred date format and a preferred time * format in WordPress' general settings in the backend user interface, we * need to retrieve that. */ $settings_format = get_option( 'date_format' ) . ' '. get_option( 'time_format' ); // $settings_format is in this example "F j, Y g:i a" /* In this example, the installation of WordPress has been set to Italian, * and the final result is "Maggio 30, 2019 10:06 am" */ return date_i18n( $settings_format, $seconds_since_local_1_jan_1970 ); }
References:
- WordPress'
get_date_from_gmt
docs DateTimeZone
docs in php.netDateTime
docs in php.net, includinggetTimestamp
- WordPress'
date_i18n
docs - It's worth remembering that WordPress runs
date_default_timezone_set( 'UTC' );
regardless of what timezone the administrator selected in the user interface, so bear that in mind when determining the behaviour of built-in PHP functions. Seedate_default_timezone_set
docs in php.net.
-
- 2015-02-16
Ajoutez un décalage defuseau horaire à votre horodatage.
$offset = get_option( 'gmt_offset' ) * HOUR_IN_SECONDS; return date_i18n( get_option( 'date_format' ), $ts + $offset );
oumieux;
$tz = new DateTimeZone( get_option( 'timezone_string' ) ); $offset_for_that_time = timezone_offset_get ( $tz , new DateTime("@{$ts}") ); return date_i18n ( get_option( 'date_format' ), $ts + offset_for_that_time );
Add timezone offset to your timestamp.
$offset = get_option( 'gmt_offset' ) * HOUR_IN_SECONDS; return date_i18n( get_option( 'date_format' ), $ts + $offset );
or better;
$tz = new DateTimeZone( get_option( 'timezone_string' ) ); $offset_for_that_time = timezone_offset_get ( $tz , new DateTime("@{$ts}") ); return date_i18n ( get_option( 'date_format' ), $ts + offset_for_that_time );
-
- 2015-12-28
Voici ce qui semblefonctionner surmamachine (aucun des autrestrucsn'afonctionné):
$tz = new DateTimeZone(get_option('timezone_string')); $dtz = new DateTimeZone('GMT'); foreach($posts as $key => $post){ $gmt_date = DateTime::createFromFormat('Y-m-d H:i:s', $post->PostDateGMT, $dtz); $gmt_date->setTimeZone($tz); $posts[$key]->PostDateGMT = $gmt_date->format('Y-m-d H:i:s'); }
Code d'origine: https://www.simonholywell.com/post/2013/12/convert-utc-to-local-time/
Iln'utilisepas
date_l18n()
maisje suppose que l'onpourrait l'utiliserplustard ...This is what seems to work on my machine (none of the other stuff worked):
$tz = new DateTimeZone(get_option('timezone_string')); $dtz = new DateTimeZone('GMT'); foreach($posts as $key => $post){ $gmt_date = DateTime::createFromFormat('Y-m-d H:i:s', $post->PostDateGMT, $dtz); $gmt_date->setTimeZone($tz); $posts[$key]->PostDateGMT = $gmt_date->format('Y-m-d H:i:s'); }
Original code: https://www.simonholywell.com/post/2013/12/convert-utc-to-local-time/
It's not using
date_l18n()
but I guess one could use it later-on...
J'ai unetâche cron WordPress quienvoiepériodiquement une-mailet enregistre l'horodatage lorsqu'il a étéenvoyéen option,et j'aimerais afficher une date sur unepage deparamètres.Quelque chose comme "Le derniere-mail a étéenvoyé le" x "".Je suis sur la côte ouest des États-Unis,doncnotretempsest actuellement à sept heures de UTC.
Ma sortie attendue de date_i18n (),en luipassant l'horodatage,serait une dateformatée localement avec un ajustement de sept heurespar rapport à UTC.Cependant,il renvoie l'heureen UTC.Mêmeessayer d'obtenir l'heure actuellene renvoiepas ce queje pense être le résultat attendu.
Parexemple:
echo date_i18n('F d, Y H:i');
affiche le 05 avril 2013 11:36 commeprévu,maisecho date_i18n('F d, Y H:i',time());
affiche le 05 avril 2013 18:36.Est-ceintentionnel?Commentpuis-je renvoyer une dateformatée localement àpartir d'un horodatagepréexistant?Mercipourtoute aide.