Note that there are some explanatory texts on larger screens.

plurals
  1. POHow to properly format/convert datetime based on current locale?
    text
    copied!<p>I have this code:</p> <pre><code>$dateTime = new DateTime('@'.strtotime('+30 minutes')); $dateTime-&gt;setTimezone(new DateTimeZone($someModel-&gt;timezone)); $otherModel-&gt;send_at = $dateTime-&gt;format($otherModel-&gt;getDateTimeFormat()); </code></pre> <p>Where <code>$otherModel-&gt;getDateTimeFormat()</code> returns <code>M/d/yy h:mm a</code> which is fine because it is based on the current Yii locale which is based on CLDR as far as i know. </p> <p>Now, when i pass this format to PHP's <code>DateTime::format()</code> class method [<code>$dateTime-&gt;format($otherModel-&gt;getDateTimeFormat())</code>] i get this result: <code>Dec/06/1313 03:1212 pm</code> which is looking weird because the format that php accepts for date/datetime is not the same as the one Yii is using in it's locales. </p> <p>How should one fix such issue? </p> <p>This is the fix: </p> <pre><code>$dateTime = new DateTime('@'.strtotime('+30 minutes')); $dateTime-&gt;setTimezone(new DateTimeZone($someModel-&gt;timezone)); // get a timestamp from the current date that also knows about the offset. $timestamp = CDateTimeParser::parse($dateTime-&gt;format('Y-m-d H:i:s'), 'yyyy-MM-dd HH:mm:ss'); // now format using Yii's methods and format type $otherModel-&gt;send_at = Yii::app()-&gt;dateFormatter-&gt;formatDateTime($timestamp, 'short', 'short'); </code></pre> <p>The idea is to use the PHP's <code>DateTime::format()</code> method to extract the timestamp that has taken into consideration the user timezone. Then, based on this timestamp, format according to Yii datetime formatting.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload