iOS中时间与时间戳的相互转化
//獲取當(dāng)前系統(tǒng)時(shí)間的時(shí)間戳
#pragma mark - 獲取當(dāng)前時(shí)間的 時(shí)間戳
+(NSInteger)getNowTimestamp
{
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateStyle:NSDateFormatterMediumStyle];
[formatter setTimeStyle:NSDateFormatterShortStyle];
//設(shè)置你想要的格式,hh與HH的區(qū)別:分別表示12小時(shí)制,24小時(shí)制
[formatter setDateFormat:@"YYYY-MM-dd HH:mm:ss"];
//設(shè)置時(shí)區(qū),這個(gè)對(duì)于時(shí)間的處理有時(shí)很重要
NSTimeZone* timeZone = [NSTimeZone timeZoneWithName:@"Asia/Beijing"];
[formatter setTimeZone:timeZone];
//現(xiàn)在時(shí)間
NSDate *datenow = [NSDate date];
NSLog(@"設(shè)備當(dāng)前的時(shí)間:%@",[formatter stringFromDate:datenow]);
//時(shí)間轉(zhuǎn)時(shí)間戳的方法:
NSInteger timeSp = [[NSNumber numberWithDouble:[datenow timeIntervalSince1970]] integerValue];
NSLog(@"設(shè)備當(dāng)前的時(shí)間戳:%ld",(long)timeSp); //時(shí)間戳的值
return timeSp;
}
//將某個(gè)時(shí)間轉(zhuǎn)化成時(shí)間戳
#pragma mark - 將某個(gè)時(shí)間轉(zhuǎn)化成時(shí)間戳
+(NSInteger)timeSwitchTimestamp:(NSString *)formatTime andFormatter:(NSString *)format
{
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateStyle:NSDateFormatterMediumStyle];
[formatter setTimeStyle:NSDateFormatterShortStyle];
//(@"YYYY-MM-dd hh:mm:ss")設(shè)置你想要的格式,hh與HH的區(qū)別:分別表示12小時(shí)制,24小時(shí)制
[formatter setDateFormat:format];
NSTimeZone* timeZone = [NSTimeZone timeZoneWithName:@"Asia/Beijing"];
[formatter setTimeZone:timeZone];
//將字符串按formatter轉(zhuǎn)成nsdate
NSDate* date = [formatter dateFromString:formatTime];
//時(shí)間轉(zhuǎn)時(shí)間戳的方法:
NSInteger timeSp = [[NSNumber numberWithDouble:[date timeIntervalSince1970]] integerValue];
NSLog(@"將某個(gè)時(shí)間轉(zhuǎn)化成 時(shí)間戳&&&&&&&timeSp:%ld",(long)timeSp); //時(shí)間戳的值
return timeSp;
}
//將某個(gè)時(shí)間戳轉(zhuǎn)化成時(shí)間
#pragma mark - 將某個(gè)時(shí)間戳轉(zhuǎn)化成 時(shí)間
+(NSString *)timestampSwitchTime:(NSInteger)timestamp andFormatter:(NSString *)format
{
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateStyle:NSDateFormatterMediumStyle];
[formatter setTimeStyle:NSDateFormatterShortStyle];
//(@"YYYY-MM-dd hh:mm:ss")設(shè)置你想要的格式,hh與HH的區(qū)別:分別表示12小時(shí)制,24小時(shí)制
[formatter setDateFormat:format];
NSTimeZone *timeZone = [NSTimeZone timeZoneWithName:@"Asia/Beijing"];
[formatter setTimeZone:timeZone];
NSDate *confromTimesp = [NSDate dateWithTimeIntervalSince1970:timestamp];
NSLog(@"1296035591 = %@",confromTimesp);
NSString *confromTimespStr = [formatter stringFromDate:confromTimesp];
//NSLog(@"&&&&&&&confromTimespStr = : %@",confromTimespStr);
return confromTimespStr;
}
總結(jié)
以上是生活随笔為你收集整理的iOS中时间与时间戳的相互转化的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: 建设银行节假日休息吗?建设银行节假日上班
- 下一篇: 核盾网络验证分析