zoukankan      html  css  js  c++  java
  • ruby -- 基础学习(四)TimeDate处理

     TimeDate格式化输出:

    DateTime.parse(Time.now.to_s).strftime('%Y-%m-%d %H:%M:%S').to_s   #就是按照2013-8-16 16:42:13的格式输出 

    如果只想输出日期,而不要输出具体时间

    DateTime.parse(Time.now.to_s).strftime('%Y-%m-%d').to_s   #就是按照2013-8-16格式输出 

    反向格式化(将字符串转化为日期格式):

    DateTime.parse(params['date']).strftime('%Y-%m-%d %H:%M:%S').to_s 

    接下来介绍rails自带的TimeDate格式

    如果你忘记了rails自带的TimeDate格式,那么在命令行输入:

    > rake date_formats

    执行命令后,可以看到如下

     1 Date
     2 ====
     3 db:'%Y-%m-%d'         2009-12-04
     4 short:'%e %b'         4 Dec
     5 number:'%Y%m%d'       20091204
     6 long:'%B %e, %Y'      December 4, 2009
     7 long_ordinal:'&proc'  December 4th, 2009
     8 rfc822:'%e %b %Y'     4 Dec 2009
     9 
    10 DateTime
    11 ========
    12 db:'%Y-%m-%d'         2009-12-04 15:38:38
    13 short:'%e %b'         04 Dec 15:38
    14 number:'%Y%m%d'       20091204153838
    15 long:'%B %e, %Y'      December 04, 2009 15:38
    16 long_ordinal:'&proc'  December 4th, 2009 15:38
    17 rfc822:'%e %b %Y'     Fri, 04 Dec 2009 15:38:38 +0800
    18        
    19 Time
    20 ====
    21 short:'%d %b %H:%M'            04 Dec 15:38
    22 db:'%Y-%m-%d %H:%M:%S'         2009-12-04 15:38:38
    23 number:'%Y%m%d%H%M%S'          20091204153838
    24 long:'%B %d, %Y %H:%M'         December 04, 2009 15:38
    25 long_ordinal:'&proc'           December 4th, 2009 15:38
    26 rfc822:'%a, %d %b %Y %H:%M:%S %z'  Fri, 04 Dec 2009 15:38:38 中国标准时间
    27 time:'%H:%M'                   15:38

    简单的格式化例子: Time.now.to_s(:db) #格式为2013-8-16

    接下来介绍,集成多种方式输出

    1 # config/initializers/date_time_formats.rb  
    2 Time::DATE_FORMATS.merge!(  
    3   :full => '%B %d, %Y at %I:%M %p',  
    4   :md => '%m/%d',  
    5   :mdy => '%m/%d/%y',  
    6   :time => '%I:%M %p'  
    7 ) 

    简单的格式化例子:Time.now.to_s(:full) #格式为"August 16, 2013 at 17:32 PM" 

    要是要求是当前年份,不显示年,其他的年才显示

    1 Time::DATE_FORMATS.merge!(  
    2   :friendly => lambda { |time|  
    3     if time.year == Time.now.year  
    4       time.strftime "%b #{time.day.ordinalize}"  
    5     else  
    6       time.strftime "%b #{time.day.ordinalize}, %Y"  
    7     end  
    8   }  
    9 ) 
    >> Time.now.to_s(:friendly)  
    => "August 16th"  
    >> (Time.now-2.years).to_s(:friendly)  
    => "August 16th, 2011"  

    参考原文链接:http://www.cnblogs.com/orez88/articles/1553126.html

                       http://www.iteye.com/topic/540957

  • 相关阅读:
    下拉选择框:数字从n到m
    event.target返回事件的目标节点(触发该事件的节点)
    nextSibling使用注意(html的注释)
    mysql导出 csv文件
    ie打印去掉页眉页脚
    jsp标签循环标签体
    String.format字符串格式化方法
    [**奇文共赏**补充问题] 据说看五遍能懂的人智商 > 200
    [转] ARP的处理办法!
    [转] 一张废手机卡的作用大全 (没试过)
  • 原文地址:https://www.cnblogs.com/lmei/p/3262575.html
Copyright © 2011-2022 走看看