Time Zone in Rails

  • Get All Time Zones
    Use

    ActiveSupport::TimeZone.all.each{|tz| puts "#{tz.formatted_offset}, #{tz.name}"};nil
    -11:00, American Samoa
    -11:00, International Date Line West
    -11:00, Midway Island
    -10:00, Hawaii
    -09:00, Alaska
    -08:00, Pacific Time (US & Canada)
    ... ignore the remaining ...
    

    To list all the built in time zones with Rails

  • Get Specific Time Zone
    Use

    ActiveSupport::TimeZone.new('Eastern Time (US & Canada)')
    

    To get the instance of a time zone with the name listed within the above output

  • Custom Time Zone
    When u know the offset, you can do this via

    ActiveSupport::TimeZone[5.hours + 30.minutes]
    => (GMT+05:30) Chennai
    

    But if the time zone u specified is not supported, it will return nil.

  • Parsing Time with Time Zone
    When u got the time zone using above methods, `time_zone` for example, using

    pry(main)> time_zone.parse('2014-12-30 17:40')
    => Tue, 30 Dec 2014 17:40:00 IST +05:30
    

    To parse a string like time.

  • Convert Time Zone
    Let

    time

    is the time we want to handle,

    target_time_zone

    is the target time zone we want to conver
    Using

    time.in_time_zone(target_time_zone) 

    For example:

    pry(main)> time = Time.zone.now
    => Tue, 30 Dec 2014 09:48:06 UTC +00:00
    pry(main)> time.hour
    => 9
    pry(main)> target_time_zone = ActiveSupport::TimeZone[8.hours]
    => (GMT+08:00) Beijing
    pry(main)> converted_time = time.in_time_zone(target_time_zone)
    => Tue, 30 Dec 2014 17:48:06 CST +08:00
    pry(main)> converted_time.hour
    => 17
    

    For the UTC time zone, the following code:

    time.utc

    is a quick method for converting time into TimeZone ‘UTC’

  • Daylight saving time
    Using

    time.dst?
    

    to check if a time is with daylight saving

iOS开发中的NSDate时区问题

iOS设备上获取的时间,呵呵,不好说,有时候是GMT时间(比如[NSDate date]),有时候是本地时间,比如用位置传感器传回来的时间戳。而且现在的应用国际化了,还是要考虑时区问题。

在iOS中,处理时区问题是用NSTimeZone来进行的,下面是一个简单的例子。

-(void)testTime{
    NSDate *now = [NSDate date];//根据当前系统的时区产生当前的时间,绝对时间,所以同为中午12点,不同的时区,这个时间是不同的。
    NSDateFormatter *df = [[NSDateFormatter alloc] init];
    df.timeZone = [NSTimeZone systemTimeZone];//系统所在时区
    df.dateFormat = @"yyyy-MM-dd HH:mm:ss";
    NSString *systemTimeZoneStr =  [df stringFromDate:now];
    df.timeZone = [NSTimeZone defaultTimeZone];//默认时区,貌似和上一个没什么区别
    NSString *defaultTimeZoneStr = [df stringFromDate:now];
    df.timeZone = [NSTimeZone timeZoneForSecondsFromGMT:8 * 3600];//直接指定时区
    NSString *plus8TZStr = [df stringFromDate:now];
    df.timeZone = [NSTimeZone timeZoneForSecondsFromGMT:0];//这就是GMT+0时区了
    NSString *gmtTZStr = [df stringFromDate: now];
    NSLog(@"Test Time\nSys:%@\nDefault:%@\n+8:%@\nGMT:%@",systemTimeZoneStr,defaultTimeZoneStr,plus8TZStr,gmtTZStr);
}

该函数运行的结果是:(在+8区,当地时间19:06:07运行)

Test Time
Sys:2013-06-30 19:06:07
Default:2013-06-30 19:06:07
+8:2013-06-30 19:06:07
GMT:2013-06-30 11:06:07