最近用到了时间这方面的三个功能简单地总结下:
第一:把字符串转换成时间
NSString *createStr = @"1753-01-01 00:00:00";
NSDateFormatter* formater = [[NSDateFormatteralloc]init];
[formatersetDateFormat:@"yyyy-MM-dd HH:mm:ss"];
NSDate* date = [formaterdateFromString:createStr];
第二:获得本市区的当前时间
//[NSDatedate]获取本初子午线现在的时间
//获得时区时间
NSDate *nowDate = [self getNowDateFromatAnDate:[NSDatedate]];
第三:比较两个时间的大小
NSTimeInterval nowTime = [nowDatetimeIntervalSince1970];
NSTimeInterval createTime = [ [selfgetNowDateFromatAnDate:date] timeIntervalSince1970];
//NSTimeInterval 是double的 所以可以用于计算了。
第四:时间转换时区
- (NSDate *)getNowDateFromatAnDate:(NSDate *)anyDate
{
//设置源日期时区
NSTimeZone* sourceTimeZone = [NSTimeZonetimeZoneWithAbbreviation:@"UTC"];//或GMT
//设置转换后的目标日期时区
NSTimeZone* destinationTimeZone = [NSTimeZonelocalTimeZone];
//得到源日期与世界标准时间的偏移量
NSInteger sourceGMTOffset = [sourceTimeZonesecondsFromGMTForDate:anyDate];
//目标日期与本地时区的偏移量
NSInteger destinationGMTOffset = [destinationTimeZonesecondsFromGMTForDate:anyDate];
//得到时间偏移量的差值
NSTimeInterval interval = destinationGMTOffset - sourceGMTOffset;
//转为现在时间
NSDate* destinationDateNow = [[NSDatealloc]initWithTimeInterval:intervalsinceDate:anyDate];
return destinationDateNow;
}
第五:获取今天之后的日期(明天为例)
//获得毫秒
NSTimeInterval createTime = [Date timeIntervalSince1970];
//加到明天-24为小时-3600为秒数
createTime = createTime+(24*3600);
//把毫秒转换成日期
newDate = [NSDate dateWithTimeIntervalSince1970:createTime];
如果有什么错误欢迎私信我,如果有更好地方法也一定要告诉我哦~
感谢你的观看,学以致用更感谢。