Foundation框架之字符串和日期

字符串

NSString

- (NSString *)substringFromIndex:(NSUInteger)from;//截取字符串從from到[string length]位置
- (NSString *)substringToIndex:(NSUInteger)to; //截取字符串從0到to位置
- (NSString *)substringWithRange:(NSRange)range;//按照range范圍截取字符串

string = [string uppercaseString];  // 將string轉成大寫
string = [string lowercaseString];  // 將string轉成小寫

BOOL ret1 = [string hasPrefix:@"He”]; // 判斷string 是否以@“He”開頭
BOOL ret2 = [string hasSuffix:@"hhh"];  // 判斷string 是否以@“hhh”結尾

NSRange pos = [string rangeOfString:@"iOS"]; // 獲取字符串@"iOS"首次出現的位置

- (unichar)characterAtIndex:(NSUInteger)index;// 指定索引位置的字符。

常見開發需求

  • 判斷字符串為nil或者為@“"
//當字符串為nil的時候,執行[testStr length] 時同樣返回0
if ([testStr length] == 0) {

 }

【思考】當服務端返回testStr = @“ ”;時,上面判斷就有問題了。
解決方案:先trim去空格然后再判斷。

NSString *test3 = [testStr stringByTrimmingCharactersInSet:[NSCharacterSetwhitespaceCharacterSet] ];
if ([test3 length] == 0) {
        NSLog(@"判斷成功");
    }
  • 判斷字符串1中包含字符串2
NSString *string = @"http://upload-images.jianshu.io/upload_images/783355-c0fbbdc98cbe6c99.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240";
if ([string containsString:@"http:"]) { 
     NSLog(@"這個是網絡圖片");}
 else {  NSLog(@"這個是本地圖片");
}

【注意】containsString出現在iOS8以后,所以在iOS7系統上程序必定崩潰
通常解決方法

if ([string rangeOfString:@"http:"].location == NSNotFound) {   
     NSLog(@"這個是本地圖片");} 
else {  
    NSLog(@"這個是網絡圖片");
}
  • NSString轉換成NSData對象
NSString* str = @"teststring";NSData* data = [str dataUsingEncoding:NSUTF8StringEncoding];
 NSString *appName = [infoDictionary objectForKey:@"CFBundleName"];
    NSString *jsonPath = [[NSBundle mainBundle] pathForResource:appName ofType:@"json"];
    NSDictionary *jsonDict = @{};
    if(jsonPath){
        NSData *jsonData = [NSData dataWithContentsOfFile:jsonPath];
        NSError *error;
        jsonDict = [NSJSONSerialization JSONObjectWithData:jsonData options:kNilOptions error:&error];
    }

NSMutableString

[str appendString:@",appendingStr!"];
[str appendFormat:@"%@。",@"appendingStr!"];
[str insertString:  atIndex:]; //插入字符串到指定索引
deleteCharactersInRange:NSMakeRange //刪除范圍內字符串
replaceCharactersInRange:NSMakeRange //替代字符串。

copy和mutableCopy的區別

mutableCopy和copy的區別

日期與時間

1.地區時間和時區時間

#地區時間
NSLocale* locale = [NSLocale currentLocale];//當前地區
NSString* str = [date1 descriptionWithLocale:locale];//根據local獲取當前時間字符串。
//指定地區
 NSLocale* locales[] = {[[NSLocale alloc]initWithLocaleIdentifier:@"zh_CN"],
        [[NSLocale alloc]initWithLocaleIdentifier:@"en_US"]};
例:
 NSString *str1 = [date description];
 NSString *str2 = [date descriptionWithLocale:locale];//根據時區獲
  NSLog(@"description:%@,descriptionWithLocale:%@",str1,str2);
//手機語言為英文
//description:2016-04-06 05:36:08 +0000,descriptionWithLocale:Wednesday, April 6, 2016 at 1:36:08 PM China Standard Time
//手機語言為中文的結果
//description:2016-04-06 05:38:30 +0000,descriptionWithLocale:2016年4月6日 星期三 中國標準時間 下午1:38:30
#時區
NSTimeZone *timeZone = [NSTimeZone systemTimeZone];//系統所在時區
NSTimeZone *timeZone = [NSTimeZone timeZoneForSecondsFromGMT:0 * 3600];//直接指定時區 

【附】地區識別碼
zh-cn 簡體中文 zh-tw 繁體中文 da-dk 丹麥語 nl-nl 荷蘭語
en-us 英語 fi-fi 芬蘭語 fr-fr 法語 de-de 德語 it-it 意大利
ja-jp 日語 ko-kr 朝鮮語 nb-no 挪威語 pt-br 葡萄牙語 es-es 西班牙語 es-us 西班牙語(美國) sv-se 瑞典語

2. 初始化和時間差

#- (instancetype)initWithTimeInterval:(NSTimeInterval)secsToBeAdded sinceDate:(NSDate *)date;
//[NSDate date]獲取當前時間的date對象
//獲取從當前時間開始,一天之后的日期
NSDate* date2 =[[NSDate alloc]initWithTimeInterval:3600*24
 sinceDate:[NSDate date]];NSLog(@"%@",date2);//2016-04-07 05:36:08 +0000
//[注]:用date對象調用+ (instancetype)dateWithTimeInterval:(NSTimeInterval)secsToBeAdded sinceDate:(NSDate *)date;
#- (instancetype)initWithTimeIntervalSinceNow:(NSTimeInterval)secs;
NSDate* date2 =[[NSDate alloc]initWithTimeIntervalSinceNow:3600*24];
NSLog(@"%@",date2);//2016-11-18 09:38:57 +0000
//[注]:用date對象調用+ (instancetype)dateWithTimeIntervalSinceNow:(NSTimeInterval)secs;
#- (instancetype)initWithTimeIntervalSince1970:(NSTimeInterval)secs;
//獲取從1970年1月1日開始,20年后的日期
NSDate* date4 = [[NSDate alloc]initWithTimeIntervalSince1970:3600*24*366*20];
NSLog(@"%@",date4);//1990-01-16 00:00:00 +0000
//[注]:用date對象調用+ (instancetype)dateWithTimeIntervalSince1970:(NSTimeInterval)secs;
#- (id) initWithTimeIntervalSinceReferenceDate:(NSTimeInterval) secs; 
//從2001年1月1日0時0分0秒開始secs秒后的日期。
//[注]:用date對象調用+ (instancetype)dateWithTimeIntervalSinceReferenceDate:(NSTimeInterval)ti;
#- (NSTimeInterval)timeIntervalSinceDate:(NSDate *)anotherDate;

3. 時間的比較

     - (NSDate *)earlierDate:(NSDate *)anotherDate;//返回更早的那個時間
     - (NSDate *)laterDate:(NSDate *)anotherDate;//返回相對較晚的時間
     - (NSComparisonResult)compare:(NSDate *)other;
      //  ==                         NSOrderedSame           0
      //  >  anotherDate is earlier, NSOrderedDescending     1
      //  <  anotherDate is later,    NSOrderedAscending.   -1
     - (BOOL)isEqualToDate:(NSDate *)otherDate;

4.格式化時間

NSDateFormatter是NSFormatter的子類,另,NSFormatter的用途是“將數據在字符串與特定類型的對象之間轉換”,目前NSFormatter只有兩個子類NSNumberFormatter和NSDateFormatter。
主要作用是NSDate和NSString之間進行轉換。

開發常見需求

  • 1.將時間戳轉化為指定格式的時間字符串。
//*時間戳*是指格林威治時間1970年01月01日00時00分00秒(北京時間1970年01月01日08時00分00秒)起至現在的總秒數。
NSDate *date = [[NSDate alloc]initWithTimeIntervalSince1970:[bookDate longLongValue]/1000.0];
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init] ;
dateFormatter.dateFormat = @"yyyy-MM-dd HH:mm:ss";//注意MM表示月份mm表示時間,HH:0~23時,hh:1~12小時
NSString *currentDateStr = [dateFormatter stringFromDate:date];
  • 2.NSString轉化為NSDate。
    NSString *str = @"2014年03月11日 04:32:33 +0000";
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    formatter.dateFormat = @"yyyy年MM月dd日 hh:mm:ss ZZZ";
    NSDate *newDate = [formatter dateFromString:str];
    NSLog(@"newDate:%@",newDate);

【注意】對于轉換過程中出現結果不正確的問題注意以下幾點
1.formatter.dateFormat = @"yyyy年MM月dd日 hh:mm:ss ZZZ";自定義的格式化字符串必須與給定的字符串str格式相同
2.得到小時不正確就是時區的問題所以字符串末尾帶上時區+0000(GMT)格式化規則字符串末尾帶上 ZZZ

  • 3.從NSDate對象中獲取年、月、日、時、分、秒 ······。
NSDateComponents *components = [[NSCalendar currentCalendar] components:NSCalendarUnitDay | NSCalendarUnitMonth | NSCalendarUnitYear 
fromDate:[NSDate date]];
NSInteger day = [components day];
NSInteger month = [components month];
NSInteger year = [components year];

【附錄】上面例子中- (NSDateComponents *)components:(NSCalendarUnit)unitFlags fromDate:(NSDate *)date;
NSCalendarUnit對象包括 :紀元、年、月、日、時、分、秒、星期等
如下:
NSCalendarUnitEra NSCalendarUnitYear NSCalendarUnitMonth NSCalendarUnitDay NSCalendarUnitHour NSCalendarUnitMinute NSCalendarUnitSecond NSCalendarUnitWeekday NSCalendarUnitWeekdayOrdinal

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容