1、NSString轉(zhuǎn)NSDate
//需要轉(zhuǎn)換的字符串
NSString *dateString = @"2015-06-26 08:08:08";
//設(shè)置轉(zhuǎn)換格式
NSDateFormatter *formatter = [[NSDateFormatter alloc] init] ;
[formatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
//NSString轉(zhuǎn)NSDate
NSDate *date=[formatter dateFromString:dateString];
注意:
(1)NSDateFormatter常用的格式有:
yyyy-MM-dd HH:mm:ss.SSS
yyyy-MM-dd HH:mm:ss
yyyy-MM-dd
MM dd yyyy
(2)NSDateFormatter格式化參數(shù)如下:
G: 公元時(shí)代,例如AD公元
yy: 年的后2位
yyyy: 完整年
MM: 月,顯示為1-12
MMM: 月,顯示為英文月份簡(jiǎn)寫,如 Jan
MMMM: 月,顯示為英文月份全稱,如 Janualy
dd: 日,2位數(shù)表示,如02
d: 日,1-2位顯示,如 2
EEE: 簡(jiǎn)寫星期幾,如Sun
EEEE: 全寫星期幾,如Sunday
aa: 上下午,AM/PM
H: 時(shí),24小時(shí)制,0-23
K:時(shí),12小時(shí)制,0-11
m: 分,1-2位
mm: 分,2位
s: 秒,1-2位
ss: 秒,2位
S: 毫秒
2、NSDate轉(zhuǎn)NSString
//獲取系統(tǒng)當(dāng)前時(shí)間
NSDate *currentDate = [NSDate date];
//用于格式化NSDate對(duì)象
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
//設(shè)置格式:zzz表示時(shí)區(qū)
[dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss zzz"];
//NSDate轉(zhuǎn)NSString
NSString *currentDateString = [dateFormatter stringFromDate:currentDate];
//輸出currentDateString
NSLog(@"%@",currentDateString);
3、將時(shí)間戳轉(zhuǎn)換為NSDate類型
-(NSDate *)getDateTimeFromMilliSeconds:(long long) miliSeconds{
NSTimeInterval tempMilli = miliSeconds;
//時(shí)間戳轉(zhuǎn)化為時(shí)間后會(huì)差8個(gè)時(shí)區(qū),需要將tempMilli-28800之后再轉(zhuǎn)化為毫秒
NSTimeInterval seconds = tempMilli-28800i/1000.0;//這里的.0一定要加上,不然除下來(lái)的數(shù)據(jù)會(huì)被截?cái)鄬?dǎo)致時(shí)間不一致
NSLog(@"傳入的時(shí)間戳=%f",seconds);
return [NSDate dateWithTimeIntervalSince1970:seconds];
}
4、將NSDate類型的時(shí)間轉(zhuǎn)換為時(shí)間戳,從1970/1/1開始
-(long long)getDateTimeTOMilliSeconds:(NSDate *)date time{
NSTimeInterval interval = [datetime timeIntervalSince1970];
NSLog(@"轉(zhuǎn)換的時(shí)間戳=%f",interval);
long long totalMilliseconds = interval*1000 ;
NSLog(@"totalMilliseconds=%llu",totalMilliseconds);
return totalMilliseconds;
轉(zhuǎn)換工具類的方法:
//NSDate轉(zhuǎn)NSString
+ (NSString *)stringFromDate:(NSDate *)date
{
//獲取系統(tǒng)當(dāng)前時(shí)間
NSDate *currentDate = [NSDate date];
//用于格式化NSDate對(duì)象
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
//設(shè)置格式:zzz表示時(shí)區(qū)
[dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss zzz"];
//NSDate轉(zhuǎn)NSString
NSString *currentDateString = [dateFormatter stringFromDate:currentDate];
//輸出currentDateString
NSLog(@"%@",currentDateString);
return currentDateString;
}
//NSString轉(zhuǎn)NSDate
+ (NSDate *)dateFromString:(NSString *)string
{
//需要轉(zhuǎn)換的字符串
NSString *dateString = @"2015-06-26 08:08:08";
//設(shè)置轉(zhuǎn)換格式
NSDateFormatter *formatter = [[NSDateFormatter alloc] init] ;
[formatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
//NSString轉(zhuǎn)NSDate
NSDate *date=[formatter dateFromString:dateString];
return date;
}