Reputation: 2153
I'm aware this subject has been covered numerous times. Fast answer is always "the later the better". But I'm unsure just how soon it'd be considered bad practice.
I'm using datetimes all over my app. If I leave it to the very last moment i.e. right before sending data to the views, I'll have to do boring repetitive code for every single datetime like that:
$dateOBJ = new DateTime($date);
$timezoneOBJ = new DateTimeZone($user_timezone);
$dateOBJ->setTimezone($timezoneOBJ)->format($my_format);
When I could do just once in the beginning of the script:
date_default_timezone_set($user_timezone);
And convert all fields right after (or during, if I was to use SQL functions) querying from UTC to user's. Therefore, a single model routine would deal with it for me and I'd never be worried about it again, even for form inputs.
Why is that bad practice?
Upvotes: 0
Views: 129
Reputation: 1561
As per my own opinion always save the time in database for a fixed time zone, and at time of display to display it according to users time zone. I don't think it have to be considered as a bad practice. As it's more relevant to show users information with respect to there own time zone .
Upvotes: 0
Reputation: 522626
A timestamp or date/time value is an absolute point in time, a precise point in human history. It doesn't matter how this timestamp is stored exactly, there are many formats which all resolve to the same point in time.
A human-readable time format in a specific timezone in a locale-specific format is just a very specific way of presenting that point in time to the user. This is inherently a presentation layer thing, not something the model is dealing with.
Maybe as a better example, take the numeric value 123456.789
. This is an absolute numerical value in a pure mathematical sense. This is the value that you base calculations on in your model. However, in the UI, this number may be presented as "123,456.789" or "123.456,789" or "12,34,56.789" or any other specific formatting, depending on what the user expects. You'd only format it this way right in your templates:
<p><?php echo number_format($number); ?></p>
You should do the same with timestamps for the same reasons. If you think the code to do so is too long, then make it shorter:
<p><?php echo format_my_date($date); ?></p>
or:
<p><?php echo $myCustomDateObject->formatLocal($locale); ?></p>
or:
$dateTimeFormatter = new MyDateTimeFormatter($userLocale, $userTimezone);
...
<p><?php echo $dateTimeFormatter->format($date); ?></p>
Upvotes: 1