zoukankan      html  css  js  c++  java
  • ios 如何获得系统时间和日期

                                                         iphone 如何获得系统时间和日期

    代码如下:

           

     #import <time.h>

    1。获得当前的系统时间和日期

    [cpp] view plaincopy
     
    1. //获得系统时间  
    2. NSDate *  senddate=[NSDate date];  
    3. NSDateFormatter  *dateformatter=[[NSDateFormatter alloc] init];  
    4. [dateformatter setDateFormat:@"HH:mm"];  
    5. NSString *  locationString=[dateformatter stringFromDate:senddate];  
    6. //[dateformatter setDateFormat:@"YYYY-MM-dd-HH-mm-ss"];  
    7. //NSString *  morelocationString=[dateformatter stringFromDate:senddate];  
    8.   
    9. //获得系统日期  
    10. NSCalendar  * cal=[NSCalendar  currentCalendar];  
    11. NSUInteger  unitFlags=NSDayCalendarUnit|NSMonthCalendarUnit|NSYearCalendarUnit;  
    12. NSDateComponents * conponent= [cal components:unitFlags fromDate:senddate];  
    13. NSInteger year=[conponent year];  
    14. NSInteger month=[conponent month];  
    15. NSInteger day=[conponent day];  
    16. NSString *  nsDateString= [NSString  stringWithFormat:@"%4d年%2d月%2d日",year,month,day];  
    17.   
    18. [dateformatter release];  

    2。从字符串来获得NSDate

        

    [cpp] view plaincopy
     
    1. string  strYear="1988";  
    2. string  strMonth="09";  
    3. string  strDay="18";  
    4. string  strHour="5";  
    5. string  strMinutes="18";  
    6. string  strSec="20";  
    7.               
    8.               
    9.           
    10. morelocationString=[NSString stringWithFormat:@"%s-%s-%s-%s-%s-%s",strYear.c_str(),strMonth.c_str(),  
    11.                                 strDay.c_str(),strHour.c_str(),strMinutes.c_str(),strSec.c_str()];  
    12.               
    13.               
    14.             //根据时间字符串获得NSDate  
    15.             NSDateFormatter  *dateformatter=[[NSDateFormatter alloc] init];  
    16.             [dateformatter setDateFormat:@"YYYY-MM-dd-HH-mm-ss"];  
    17.             NSDate  * oldDate=[dateformatter dateFromString:morelocationString];  

       通过上面的代码,获得了NSDate。

    3。 从GMT时间,得到本地时间

      

    [cpp] view plaincopy
     
    1. NSDate  * oldDate=[dateformatter dateFromString:morelocationString];  
    2.               
    3.               
    4.             NSTimeInterval  timeZoneOffset=[[NSTimeZone systemTimeZone] secondsFromGMT];  
    5.             NSDate  * newDate=[oldDate dateByAddingTimeInterval:timeZoneOffset];  
  • 相关阅读:
    iOS Xcode工程目录的 folder 和 group的区别(蓝色和黄色文件夹的区别)
    携程App的网络性能优化实践
    iOS: NSObject中执行Selector的相关方法
    去空格 whitespaceAndNewlineCharacterSet
    iOS UIButton 设置图片文字垂直排列
    程序启动的完整过程
    iOS:友盟SDK第三方登录 分享及友盟统计的使用
    ios8 UITableView设置 setSeparatorInset:UIEdgeInsetsZero不起作用的解决办法
    判断uiscrollView滑到底部
    ios模拟器键盘不弹出
  • 原文地址:https://www.cnblogs.com/bmate/p/3200713.html
Copyright © 2011-2022 走看看