IOS_Object-C 學習筆__ NSString 轉換成 NSData ( Convert NSString to NSData )
如何把一個字串的格式內容
如何把一個字串格式內容,轉換成時間的格式!
從這個範例來看,先初始化我們要用的物件
然後在設定它的格式
接下來透過 dateFromString 來把要轉換的字串帶進去
這樣就能把文字轉換成Date的格式
Convert NSString to NSData
Change NSString type to NSData!
First need initialized object use NSDateFormatter.
Second setting data format.
Third use "dateFromString" change the NSString type.
//=====================//
NSString *dateStr = @"2017-8-3";
//sample1
NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
[dateFormat setDateFormat:@"YY-MM-dd"];
NSDate *date = [dateFormat dateFromString:dateStr];
NSLog(@"dateFormat1 :%@",date);
//sample2
[dateFormat setDateFormat:@"MM-dd-YYYY"];
NSString* temp = [dateFormat stringFromDate:date];
NSLog(@"dateFormat2 :%@",temp);
//sample3
NSString *Date = @"2017-01-24";
NSDateFormatter *useDate = [[NSDateFormatter alloc] init];
[useDate setDateFormat:@"YYYY-MM-dd"];
NSDate *dd = [useDate dateFromString:Date];
NSLog(@"dateFormat3 :%@",dd);
//=====================//
NSString *dateStr = @"2017-8-3";
//sample1
NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
[dateFormat setDateFormat:@"YY-MM-dd"];
NSDate *date = [dateFormat dateFromString:dateStr];
NSLog(@"dateFormat1 :%@",date);
//sample2
[dateFormat setDateFormat:@"MM-dd-YYYY"];
NSString* temp = [dateFormat stringFromDate:date];
NSLog(@"dateFormat2 :%@",temp);
//sample3
NSString *Date = @"2017-01-24";
NSDateFormatter *useDate = [[NSDateFormatter alloc] init];
[useDate setDateFormat:@"YYYY-MM-dd"];
NSDate *dd = [useDate dateFromString:Date];
NSLog(@"dateFormat3 :%@",dd);
留言
張貼留言