13

iOS开发:NSDate时区与格式化问题

 2 years ago
source link: https://www.isaced.com/post-175.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client
Written by
on October 11, 2012

iOS开发:NSDate时区与格式化问题

时区

今天做到DatePicker,一个按钮弹出选择的日期时间,默认的NSDate Date的显示的是格林威治标准时间GMT,在中国肯定不适用,所以要转换为中国时区+8,然后也接触到ios中的日期时间格式化。

下图为效果:

36db52415ef0a47030f7c0e1691ccf92.png

贴上代码:

    //取DatePicker选择的日期时间
    NSDate *date = [DatePicker date];
    
    //时区转换,取得系统时区,取得格林威治时间差秒
    //NSTimeInterval  timeZoneOffset=[[NSTimeZone systemTimeZone] secondsFromGMT];
    //NSLog(@"%f",timeZoneOffset/60.0/60.0);
    
    //date = [date dateByAddingTimeInterval:timeZoneOffset];
    
    //格式化日期时间
    NSDateFormatter *dateformatter=[[NSDateFormatter alloc] init];
    [dateformatter setDateFormat:@"现在日期:yyyy年MM月dd日 \n 现在时刻: HH:mm:ss             "];
    NSString * dateStr=[dateformatter stringFromDate:date];
    
    //警告弹出
    NSString * strDate = [[NSString alloc] initWithFormat:@"%@",dateStr] ;
    UIAlertView * tip = [[UIAlertView alloc] initWithTitle:@"选择时间" message:strDate delegate:self cancelButtonTitle:@"确定" otherButtonTitles: nil];
    [tip show];
    [tip release];
    
    //清理
    [dateformatter release];

这里有点疑惑的是,不加上时区转换的代码,就只有格式化日期都可以自动转换为+8时区,这是为什么呢?

关于格式化日期的格式字符串就不用说了很简单,yyyy代表年,M代表月,d代表几号,HH小时,mm分钟,ss秒,这里要提的一点是这个是区分大小写,个数不同结果也不同,在一位的时候,比如dd是09,而d就是9。


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK