在開發(fā)中砂轻,往往我們會(huì)用到時(shí)間戳這個(gè)東西,至于時(shí)間戳是個(gè)什么東西舔清,我就不去多說了体谒,因?yàn)榘俣壬虾芏唷:昧耸阊鳎裉煳液痛蠹曳窒硪幌挛以谑褂脮r(shí)間戳?xí)r的一些轉(zhuǎn)換問題。
時(shí)間戳轉(zhuǎn)日期字符串(時(shí)間戳NSString 轉(zhuǎn) 日期NSString)
代碼:
-(NSString *)timeWithTimeIntervalString:(NSString *)timeString
{
NSDate *nd = [NSDate dateWithTimeIntervalSince1970:(NSTimeInterval)[timeString integerValue]];
NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
// [dateFormat setDateFormat:@"HH:mm:ss"];
[dateFormat setDateFormat:@"yyyy-MM-dd HH:mm"];
NSString *dateString = [dateFormat stringFromDate:nd];
return dateString;
}
當(dāng)前日期轉(zhuǎn)時(shí)間戳(日期NSDate 轉(zhuǎn) 時(shí)間戳NSString)
代碼:
- (NSString *)timeToTurnTheTimestamp{
NSDate* dat = [NSDate dateWithTimeIntervalSinceNow:0];
NSTimeInterval a=[dat timeIntervalSince1970];
NSString *timeString = [NSString stringWithFormat:@"%f", a];
return timeString;
}
日期字符串轉(zhuǎn)時(shí)間戳(NSString轉(zhuǎn)時(shí)間戳NSString)
代碼:
-(NSString *)turnTheTimestampString:(NSString*) timeStr{
NSDateFormatter *formatter = [[NSDateFormatter alloc] init] ;
[formatter setDateStyle:NSDateFormatterMediumStyle];
[formatter setTimeStyle:NSDateFormatterShortStyle];
[formatter setDateFormat:@"YYYY-MM-dd"]; // ----------設(shè)置你想要的格式,hh與HH的區(qū)別:分別表示12小時(shí)制,24小時(shí)制
//設(shè)置時(shí)區(qū),這個(gè)對(duì)于時(shí)間的處理有時(shí)很重要
//例如你在國內(nèi)發(fā)布信息,用戶在國外的另一個(gè)時(shí)區(qū),你想讓用戶看到正確的發(fā)布時(shí)間就得注意時(shí)區(qū)設(shè)置,時(shí)間的換算.
//例如你發(fā)布的時(shí)間為2010-01-26 17:40:50,那么在英國愛爾蘭那邊用戶看到的時(shí)間應(yīng)該是多少呢?
//他們與我們有7個(gè)小時(shí)的時(shí)差,所以他們那還沒到這個(gè)時(shí)間呢...那就是把未來的事做了
NSTimeZone* timeZone = [NSTimeZone timeZoneWithName:@"Asia/Shanghai"];
[formatter setTimeZone:timeZone];
NSDate* date = [formatter dateFromString:timeStr]; //------------將字符串按formatter轉(zhuǎn)成nsdate
NSTimeInterval a=[date timeIntervalSince1970];
NSString *timeString = [NSString stringWithFormat:@"%f", a];
return timeString;
}
時(shí)間戳轉(zhuǎn)星期格式
代碼
- (NSString*)weekdayStringFromDate:(NSString *)timeString
{
NSDate *nd = [NSDate dateWithTimeIntervalSince1970:(NSTimeInterval)[timeString doubleValue]];
NSArray *weekdays = [NSArray arrayWithObjects: [NSNull null], @"周日", @"周一", @"周二", @"周三", @"周四", @"周五", @"周六", nil];
NSCalendar *calendar = [NSCalendar currentCalendar];
NSTimeZone *timeZone = [[NSTimeZone alloc] initWithName:@"Asia/Shanghai"];
[calendar setTimeZone: timeZone];
NSCalendarUnit calendarUnit = NSCalendarUnitWeekday;
NSDateComponents *theComponents = [calendar components:calendarUnit fromDate:nd];
return [weekdays objectAtIndex:theComponents.weekday];
}