时间戳和字符串互转

来源:互联网 发布:计算json长度工具 编辑:程序博客网 时间:2024/06/05 15:48

//注:时间格式要和自己设置的格式相同#pragma mark 时间戳转成字符串-(NSString *)getTimeWithtime:(NSInteger)time{    //时间戳转时间的方法    NSDateFormatter *formatter = [[NSDateFormatteralloc] init];    [formatter setDateStyle:NSDateFormatterMediumStyle];    [formatter setTimeStyle:NSDateFormatterShortStyle];    [formatter setDateFormat:@"YYYY年MM月dd日 HH:mm:ss"];//注:时间格式要和自己设置的格式相同    NSDate *confromTimesp = [NSDatedateWithTimeIntervalSince1970:time];    NSString *confromTimespStr = [formatterstringFromDate:confromTimesp];    return confromTimespStr;}#pragma mark 字符串转换成时间戳 -(NSString *)getTimewithTime:(NSString *)time{              //    设置时间显示格式:              //    NSString* timeStr = @"2011-01-26 17:40:50";              time = [time stringByReplacingOccurrencesOfString:@"年"withString:@"-"];              time = [time stringByReplacingOccurrencesOfString:@"月"withString:@"-"];              time = [time stringByReplacingOccurrencesOfString:@"日"withString:@""];              NSString * timeStr = [NSStringstringWithFormat:@"%@ 00:00:00",time];              //    NSString * timeStr = time;              NSDateFormatter *formatter = [[NSDateFormatteralloc] init] ;              [formatter setDateStyle:NSDateFormatterMediumStyle];              [formatter setTimeStyle:NSDateFormatterShortStyle];              [formatter setDateFormat:@"YYYY-MM-dd HH:mm:ss"];// ----------设置你想要的格式,hh与HH的区别:分别表示12小时制,24小时制              //设置时区,这个对于时间的处理有时很重要              //例如你在国内发布信息,用户在国外的另一个时区,你想让用户看到正确的发布时间就得注意时区设置,时间的换算.              //例如你发布的时间为2010-01-26 17:40:50,那么在英国爱尔兰那边用户看到的时间应该是多少呢?              //他们与我们有7个小时的时差,所以他们那还没到这个时间呢...那就是把未来的事做了              NSTimeZone* timeZone = [NSTimeZonetimeZoneWithName:@"Asia/Shanghai"];              [formatter setTimeZone:timeZone];              NSDate* date = [formatterdateFromString:timeStr]; //------------将字符串按formatter转成nsdate              //    NSDate *datenow = [NSDate date];//现在时间,你可以输出来看下是什么格式              //    NSString *nowtimeStr = [formatter stringFromDate:datenow];//----------将nsdate按formatter格式转成nsstring              //    时间转时间戳的方法:              NSString *timeSp = [NSStringstringWithFormat:@"%f", [datetimeIntervalSince1970]];              NSLog(@"timeSp:%@",timeSp);//时间戳的值              return timeSp;          }


1 0