冒险村09 - Time format config

09 - Time format

在专案中时常会有用到显示时间的地方,可能格式只有一种,但是会散落在各个档案里,又或者是有许多种的格式。

举例来说,可能是某个前端 erb 档案需要捞这笔资料被建立的时间 (create_at),但是不想要 rails 预设给的 format 显示给使用者。

  User.first.created_at.strftime("%F %H:%M")

或者是某个 helper 里面有个判断来变更显示的格式。

  # app/helpers/user_helper.rb
  module UserHelper
    def display_last_update_password_at(last_update_password_at)
      if last_update_password_at.nil?
        I18n.t('user.labels.no_last_changed')
      else
        "#{I18n.t('user.labels.last_changed_on')} #{resource.last_update_password_at.strftime('%F %H:%M')}"
      end
    end
  end

不过这样子的做法会导致 strftime 格式会散落在许多档案里,可能 a 档案跟 b 档案的逻辑不同,但要显示的格式相同,也不能整理在一起,更不易阅读。

注: ruby 内建的 strftime 格式显示方式这边就不详细说明

虽然 rails 有提供 to_s 方法来达到这个需求

  datetime = DateTime.civil(2007, 12, 4, 0, 0, 0, 0)   # => Tue, 04 Dec 2007 00:00:00 +0000

  datetime.to_formatted_s(:db)            # => "2007-12-04 00:00:00"
  datetime.to_s(:db)                      # => "2007-12-04 00:00:00"
  datetime.to_s(:number)                  # => "20071204000000"
  datetime.to_formatted_s(:short)         # => "04 Dec 00:00"
  datetime.to_formatted_s(:long)          # => "December 04, 2007 00:00"
  datetime.to_formatted_s(:long_ordinal)  # => "December 4th, 2007 00:00"
  datetime.to_formatted_s(:rfc822)        # => "Tue, 04 Dec 2007 00:00:00 +0000"
  datetime.to_formatted_s(:iso8601)       # => "2007-12-04T00:00:00+00:00"

如果想要自己的格式来显示的话,我们可以建立 time_formats.rb 来设定、整理所有有关时间的格式。

Setting config > initializers > time_formats.rb

  # config/initializers/time_formats.rb

  Time::DATE_FORMATS[:long_zh_tw] = "%Y年%m月%d日%H时%M分"
  Time::DATE_FORMATS[:long_no_separator] = "%Y%m%d%H%M%S"
  Time::DATE_FORMATS[:hm_on_today] = "%H:%M"
  Time::DATE_FORMATS[:md_on_today_zh_tw] = "%m月%d日"

这样子在所有地方想要用到这种格式的显示,就可以 to_s 後接自己的 custom_format 了!

  # before
  User.first.created_at.strftime("%Y%m%d%H%M%S")
  
  # after
  User.first.created_at.to_s(:long_no_separator)

注: 新增 config 需要重启 server 才会吃得到唷~

参考来源

My blog


<<:  Day24 ( 游戏设计 ) 记忆大考验

>>:  CSS微动画 - Loading来了!小精灵?这个小家伙吃蛋

裸机Hyperviser大众化原因

今天来探讨裸机Hyperviser在近几年朝大众化的原因 摆脱固有平台 受够了各大云端运算服务的绑手...

Day 3:建立专案(一)

软件专案通常由许多程序码档案以及资源档组成,C++ 专案透过编译、连结产生各平台的可执行档。多数专案...

Day 11 Odoo Actions (ir.actions.act_url)

Odoo模组开发实战 目录 Action 1.1 URL Actions (ir.actions.a...

Day18# Leetcode TwoSum

接下来的 12 天,会用每天刷 leetcode 练习的方式来练习 Go 那麽话不多说,我们就进入正...

VMware Horizon Client, Compose Server, Horizon Server 每周固定时段异常无法连线 !

状况描述: esxi server 7.0.0 上面运行 vSphere Client 7.0.0 ...