dongzhang5787 2013-12-18 09:33
浏览 39

何时将UTC日期时间转换为用户的本地以获得多语言支持

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?

  • 写回答

2条回答 默认 最新

  • duanhe6718 2013-12-18 09:43
    关注

    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>
    
    评论

报告相同问题?

悬赏问题

  • ¥15 Mac系统vs code使用phpstudy如何配置debug来调试php
  • ¥15 目前主流的音乐软件,像网易云音乐,QQ音乐他们的前端和后台部分是用的什么技术实现的?求解!
  • ¥60 pb数据库修改与连接
  • ¥15 spss统计中二分类变量和有序变量的相关性分析可以用kendall相关分析吗?
  • ¥15 拟通过pc下指令到安卓系统,如果追求响应速度,尽可能无延迟,是不是用安卓模拟器会优于实体的安卓手机?如果是,可以快多少毫秒?
  • ¥20 神经网络Sequential name=sequential, built=False
  • ¥16 Qphython 用xlrd读取excel报错
  • ¥15 单片机学习顺序问题!!
  • ¥15 ikuai客户端多拨vpn,重启总是有个别重拨不上
  • ¥20 关于#anlogic#sdram#的问题,如何解决?(关键词-performance)