iOS-NSDate时间、时间戳操作

本文提供了一系列时间操作的方法,包括时间戳的获取与转换、日期格式化、时间比较等实用技巧,并详细介绍了如何处理不同时间格式之间的转换。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

#pragma mark -获取字符串形式的时间戳
-(NSString *)getTimeStampString
{
    //获取时间和时间戳
    NSDate* timeStamp = [NSDatedateWithTimeIntervalSinceNow:0];
    NSTimeInterval temp=[timeStamptimeIntervalSince1970]*1000;
    return [NSStringstringWithFormat:@"%.0f", temp];
}

#pragma mark - 时间戳转为NSString
/**
 *  @author zm
 *
 *  @brief  时间戳转为NSString
 *
 *  @param timeStamp   字符串格式的时间戳
 *  @param formatString format格式(默认yyyy-MM-dd HH:mm:ss.SSS)
 *
 *  @return 返回字符串
 */
-(NSString *)event_stringFromTimeStamp:(NSString *)timeStamp formatString:(NSString *)formatString
{
    NSDate *updatetimestamp = [selff_getDateByString:timeStamp];
    NSString *dateFormat =@"yyyy-MM-dd HH:mm:ss.SSS";
    if (formatString) {
        dateFormat = formatString;
    }
    NSDateFormatter *formatter = [[NSDateFormatteralloc]init];
    [formatter setDateStyle:NSDateFormatterMediumStyle];
    [formatter setTimeStyle:NSDateFormatterShortStyle];
    [formatter setDateFormat:dateFormat];
    NSString *dateString = [formatterstringFromDate:updatetimestamp];
    return dateString;
}

#pragma mark -获取字符串形式的当前时间(默认yyyy-MM-dd HH:mm:ss)
+(NSString *)getDateTimeString:(NSDateFormatter *)dateFormatter
{
    if (dateFormatter ==nil) {
        dateFormatter = [[NSDateFormatteralloc]init];
        [dateFormattersetDateFormat:@"yyyy-MM-dd HH:mm:ss.SSS"];
    }
    NSDate *dateNow = [NSDatedate];
    return [dateFormatterstringFromDate:dateNow];
}

#pragma mark -将字符串形式的时间转换为时间戳
+(UInt64)getTimeStampByDateString:(NSString *)dateString
{
    NSDateFormatter *XNNDateFormatter = [[NSDateFormatteralloc]init];
    [XNNDateFormattersetDateFormat:@"yyyy-MM-dd HH:mm:ss.SSS"];
    NSDate *XNNDate= [XNNDateFormatterdateFromString:dateString];
    if(XNNDate){
        return [XNNDatetimeIntervalSince1970]*1000;
    }else{
        return -99999;
    }
}

#pragma mark -字符串转为日期
- (NSDate *)stringToDate:(NSString *)strdate
{
    NSDateFormatter *dateFormatter = [[NSDateFormatteralloc] init];
    [dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    NSDate *retdate = [dateFormatter dateFromString:strdate];
    [dateFormatter release];
    return retdate;
}

#pragma mark -日期转为字符串
- (NSString *)dateToString:(NSDate *)date
{
    NSDateFormatter *dateFormatter = [[NSDateFormatteralloc] init];
    [dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    NSString *strDate = [dateFormatter stringFromDate:date];
    [dateFormatter release];
    return strDate;
}

#pragma mark -将UTC日期字符串转为本地时间字符串  
//输入的UTC日期格式2013-08-03T04:53:51+0000  
-(NSString *)getLocalDateFormateUTCDate:(NSString *)utcDate  
{  
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];  
    //输入格式  
    [dateFormatter setDateFormat:@"yyyy-MM-dd'T'HH:mm:ssZ"];  
    NSTimeZone *localTimeZone = [NSTimeZone localTimeZone];  
    [dateFormatter setTimeZone:localTimeZone];  
      
    NSDate *dateFormatted = [dateFormatter dateFromString:utcDate];  
    //输出格式  
    [dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];  
    NSString *dateString = [dateFormatter stringFromDate:dateFormatted];  
    [dateFormatter release];  
    return dateString;  
}

#pragma mark -将本地日期字符串转为UTC日期字符串  
//本地日期格式:2013-08-03 12:53:51  
//可自行指定输入输出格式  
-(NSString *)getUTCFormateLocalDate:(NSString *)localDate  
{  
   NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init]; 
    //输入格式  
    [dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];        
    NSDate *dateFormatted = [dateFormatter dateFromString:localDate];  
    NSTimeZone *timeZone = [NSTimeZone timeZoneWithName:@"UTC"];  
    [dateFormatter setTimeZone:timeZone]; 
   //输出格式 
    [dateFormatter setDateFormat:@"yyyy-MM-dd'T'HH:mm:ssZ"];  
    NSString *dateString = [dateFormatter stringFromDate:dateFormatted]; 
    [dateFormatter release]; 
    return dateString;  
} 

- (NSString *)getUTCFormatDate:(NSDate *)localDate
{
    NSDateFormatter *dateFormatter = [[NSDateFormatteralloc] init];
    NSTimeZone *timeZone = [NSTimeZonetimeZoneWithName:@"UTC"];
    [dateFormatter setTimeZone:timeZone];
    [dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss Z"];
    NSString *dateString = [dateFormatter stringFromDate:localDate];
    [dateFormatter release];
    return dateString;
}

- (NSDate *)getLocalFromUTC:(NSString *)utc
{
    NSDateFormatter *dateFormatter = [[NSDateFormatteralloc] init];
    NSTimeZone *timeZone = [NSTimeZonelocalTimeZone];
    [dateFormatter setTimeZone:timeZone];
    [dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss Z"];
    NSDate *ldate = [dateFormatter dateFromString:utc];
    [dateFormatter release];
    return ldate;
}

#pragma mark -世界标准时间UTC /GMT 转为当前系统时区对应的时间 
- (NSDate *)getNowDateFromatAnDate:(NSDate *)anyDate  
{  
    //设置源日期时区  
    NSTimeZone* sourceTimeZone = [NSTimeZone timeZoneWithAbbreviation:@"UTC"];//或GMT  
    //设置转换后的目标日期时区  
    NSTimeZone* destinationTimeZone = [NSTimeZone localTimeZone];  
    //得到源日期与世界标准时间的偏移量  
    NSInteger sourceGMTOffset = [sourceTimeZone secondsFromGMTForDate:anyDate];  
    //目标日期与本地时区的偏移量  
   NSInteger destinationGMTOffset = [destinationTimeZone secondsFromGMTForDate:anyDate];  
    //得到时间偏移量的差值  
    NSTimeInterval interval = destinationGMTOffset - sourceGMTOffset;  
   //转为现在时间  
   NSDate* destinationDateNow = [[[NSDate alloc] initWithTimeInterval:interval sinceDate:anyDate] autorelease];  
    return destinationDateNow;  
}  
    如:
     //2013-08-03T12:53:51+0800     UTC时间格式下的北京时间,可以看到北京时间= UTC + 8小时。
    NSDateFormatter *dateFormatter = [[NSDateFormatteralloc] init];
    [dateFormatter setDateFormat:@"yyyy-MM-dd'T'HH:mm:ssZ"];
    NSDate *localDate = [dateFormatter dateFromString:@"2013-08-03T04:56:52+0000"];      +0000 表示的是当前时间是个世界时间。
    [dateFormatter release];
    NSLog(@"now Time = %@",[selfgetNowDateFromatAnDate:localDate]);
结果:
2013-08-03 12:57:33.391 xxxx[2547:c07] now Time = 2013-08-03 12:56:52 +0000
 以上注意一点,在转出来后带的时间是原参数anydate的时区,因此切不可再用NSDateFormatter 转换。否则会多增加一个时区的时间值。应该使用如下来提取字符串
    NSString *str = [NSStringstringWithFormat:@"%@",[selfgetNowDateFromatAnDate:localDate]];
    NSLog(@"str = %@",str);
注NSDate对象存放的日期始终是UTC的标准时间,可以根据这个时间进行其它时间的转换。因此上面算出来的时间中时区为 +0000,如果此时再转为字符串
#pragma mark -比较时间间隔(天数)
+(NSInteger)compareOneDay:(NSDate *)oneDay withAnotherDay:(NSDate *)anotherDay
{
    NSDateFormatter *dateFormatter=[[NSDateFormatteralloc]init];
    [dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm"];
    NSTimeInterval time =[oneDaytimeIntervalSinceDate:anotherDay];
    NSInteger days=((NSInteger)time)/(3600*24);
    return days;
}

#pragma mark -比较时间间隔(ms)
+(NSInteger)compareOneTime:(NSDate *)oneTime withAnotherTime:(NSDate *)anotherTime
{
    NSDateFormatter *dateFormatter=[[NSDateFormatteralloc]init];
    [dateFormatter setDateFormat:@"HH:mm:ss"];
    NSTimeInterval time =[oneTimetimeIntervalSinceDate:anotherTime];
    //1s = 1000ms
    NSInteger timeT=((NSInteger)time) *1000;
    return timeT;
}

#pragma mark-获取当前时间的年、月、日、时、分、秒
//获取当前时间
NSDate *now = [NSDate date];
NSLog(@"now date is: %@", now);
NSCalendar *calendar = [NSCalendar currentCalendar];
NSUInteger unitFlags = NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit | NSHourCalendarUnit | NSMinuteCalendarUnit | NSSecondCalendarUnit;
NSDateComponents *dateComponent = [calendar components:unitFlags fromDate:now];
int year = [dateComponent year];
int month = [dateComponent month];
int day = [dateComponent day];
int hour = [dateComponent hour];
int minute = [dateComponent minute];
int second = [dateComponent second];
NSLog(@"year is: %d", year);
NSLog(@"month is: %d", month);
NSLog(@"day is: %d", day);
NSLog(@"hour is: %d", hour);
NSLog(@"minute is: %d", minute);
NSLog(@"second is: %d", second);

 

 

  

 

 

NSUInteger unitFlags = NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay | NSCalendarUnitHour | NSCalendarUnitMinute | NSCalendarUnitSecond;

 

 

 

<think>嗯,用户的问题是关于如何在iOS中将时间字符串转换为Unix时间戳,使用Swift或Objective-C。首先,我需要回忆一下iOS中处理日期和时间的方法。记得在Objective-C中,主要使用NSDateNSDateFormatter这些类,而在Swift中则是Date和DateFormatter。 用户提到了时间字符串转换为时间戳,所以关键步骤应该是解析字符串为日期对象,然后获取该日期的时间戳时间戳通常是自1970年1月1日以来的秒数或毫秒数,但Unix时间戳一般指的是秒数。 首先,用户可能需要使用NSDateFormatter或DateFormatter来将字符串转换为日期对象。这里需要注意设置正确的日期格式和时区,否则解析可能会出错。例如,如果时间字符串是"2023-10-05 14:30:00",对应的格式应该是"yyyy-MM-dd HH:mm:ss"。时区方面,可能需要设置为UTC或者系统当前的时区,视具体情况而定。 然后,转换得到的NSDate或Date对象,可以通过timeIntervalSince1970方法获取时间戳。不过要确认是否需要秒还是毫秒,如果是毫秒的话需要乘以1000。用户的问题里提到Unix时间戳,通常是指秒级的,所以可能不需要转换。 接下来需要分别给出Swift和Objective-C的示例代码。在Swift中,使用DateFormatter,设置dateFormat和可能的时区,然后调用date(from:)方法解析字符串,再使用timeIntervalSince1970获取时间戳。Objective-C部分类似,使用NSDateFormatter,设置相应的属性,解析得到NSDate后同样获取时间戳。 还需要考虑可能的错误处理,比如日期字符串和格式不匹配的情况,这时候解析会返回nil,需要处理可选值。另外,时区的设置是否正确也很重要,如果时间字符串是UTC时间,应该将formatter的时区设置为UTC,否则可能导致转换错误。 用户提供的参考引用里有一个Objective-C方法,dateFromUnixTimestamp:,看起来是从时间戳生成NSDate,但用户的问题相反,所以可能需要反向操作。确保示例代码正确无误,语法正确。 最后,生成相关问题的时候,可以围绕日期格式、时区处理、时间戳的精度、不同编程语言实现等方向来提问。比如如何处理不同日期格式,时区的影响,或者如何在Swift和Objective-C之间进行转换比较等等。 总结一下,回答的结构应该是先介绍使用DateFormatter/NSDateFormatter解析字符串为日期对象,然后获取时间戳,分别给出两种语言的代码示例,并提醒注意日期格式和时区的设置。最后生成相关问题,帮助用户深入理解。</think>在iOS中将时间字符串转换为Unix时间戳需要以下步骤: ### 一、Swift实现 ```swift func stringToTimestamp(dateString: String, format: String) -> TimeInterval? { let formatter = DateFormatter() formatter.dateFormat = format // 设置日期格式,如"yyyy-MM-dd HH:mm:ss" formatter.timeZone = TimeZone(abbreviation: "UTC") // 根据需求设置时区 guard let date = formatter.date(from: dateString) else { return nil } return date.timeIntervalSince1970 // 转换为秒级时间戳 } ``` ### 二、Objective-C实现 ```objective-c - (NSTimeInterval)timestampFromString:(NSString *)dateString format:(NSString *)format { NSDateFormatter *formatter = [[NSDateFormatter alloc] init]; [formatter setDateFormat:format]; // 设置日期格式 [formatter setTimeZone:[NSTimeZone timeZoneWithAbbreviation:@"UTC"]]; // 设置时区 NSDate *date = [formatter dateFromString:dateString]; return [date timeIntervalSince1970]; // 返回秒级时间戳 } ``` ### 关键要点: 1. **日期格式匹配**:`dateFormat`必须与输入字符串完全匹配(如`@"yyyy-MM-dd'T'HH:mm:ssZ"`对应ISO8601格式) 2. **时区处理**:默认使用系统时区,建议根据数据源指定时区 3. **时间戳类型**:`timeIntervalSince1970`返回双精度浮点数,包含小数秒[^1]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值