設(shè)置時(shí)間顯示格式:
NSString* timeStr =
@"2011-01-26 17:40:50";
NSDateFormatter
*formatter = [[[NSDateFormatter alloc] init] autorelease];
[formatter
setDateStyle:NSDateFormatterMediumStyle];
[formatter
setTimeStyle:NSDateFormatterShortStyle];
[formatter
setDateFormat:@"YYYY-MM-dd HH:mm:ss"]; //
----------設(shè)置你想要的格式,hh與HH的區(qū)別:分別表示12小時(shí)制,24小時(shí)制
//設(shè)置時(shí)區(qū),這個(gè)對(duì)于時(shí)間的處理有時(shí)很重要
//例如你在國(guó)內(nèi)發(fā)布信息,用戶在國(guó)外的另一個(gè)時(shí)區(qū),你想讓用戶看到正確的發(fā)布時(shí)間就得注意時(shí)區(qū)設(shè)置,時(shí)間的換算.
//例如你發(fā)布的時(shí)間為2010-01-26
17:40:50,那么在英國(guó)愛(ài)爾蘭那邊用戶看到的時(shí)間應(yīng)該是多少呢?
//他們與我們有7個(gè)小時(shí)的時(shí)差,所以他們那還沒(méi)到這個(gè)時(shí)間呢...那就是把未來(lái)的事做了
NSTimeZone* timeZone =
[NSTimeZone timeZoneWithName:@"Asia/Shanghai"];
[formatter
setTimeZone:timeZone];
NSDate* date =
[formatter dateFromString:timeStr];
//------------將字符串按formatter轉(zhuǎn)成nsdate
NSDate *datenow =
[NSDate date];//現(xiàn)在時(shí)間,你可以輸出來(lái)看下是什么格式
NSString *nowtimeStr =
[formatter
stringFromDate:datenow];//----------將nsdate按formatter格式轉(zhuǎn)成nsstring
時(shí)間轉(zhuǎn)時(shí)間戳的方法:
NSString *timeSp =
[NSString stringWithFormat:@"%d", (long)[datenow
timeIntervalSince1970]];
NSLog(@"timeSp:%@",timeSp); //時(shí)間戳的值
時(shí)間戳轉(zhuǎn)時(shí)間的方法
NSDate *confromTimesp =
[NSDate dateWithTimeIntervalSince1970:1296035591];
NSLog(@"1296035591
= %@",confromTimesp);
NSString
*confromTimespStr = [formatter stringFromDate:confromTimesp];
NSLog(@"confromTimespStr
= %@",confromTimespStr);
時(shí)間戳轉(zhuǎn)時(shí)間的方法:
NSDateFormatter* formatter = [[NSDateFormatter alloc] init];
[formatter setDateStyle:NSDateFormatterMediumStyle];
[formatter setTimeStyle:NSDateFormatterShortStyle];
[formatter setDateFormat:@"yyyyMMddHHMMss"];
NSDate *date = [formatter dateFromString:@"1283376197"];
NSLog(@"date1:%@",date);
[formatter release];
|