iOS 玩转时间(NSDate)(持续更新)

简友们,这篇文章主要是操控NSDate的一些方法 ,欢迎大家一起合力把这篇文章扩展的更完美,我的QQ是479309088,欢迎加Q交流!喜欢的点个赞!谢谢!


01.比较当前时间和自定义的时间:两个时间差:天-时-分

- (void)getTimeDistance {

NSDateFormatter *formatter = [[NSDateFormatter alloc] init];

[formatter setDateFormat:@"YYYY-MM-dd HH:mm:ss"];//设置你想要的格式,hh与HH的区别:分别表示12小时制,24小时制

NSTimeZone* timeZone = [NSTimeZone timeZoneWithAbbreviation:@"UTC"];

[formatter setTimeZone:timeZone];

/**

*  当前时间

*/

NSDate *datenow = [NSDate date];

/**

*自定义一个字符串的时间

*/

NSString *datestring = @"2016-05-08 18:33:00";

NSDateFormatter * dm = [[NSDateFormatter alloc]init];

[dm setDateFormat:@"YYYY-MM-dd HH:mm:ss"];

NSDate * newdate = [dm dateFromString:datestring];

/**

* bb: 计算出当前时间和自定义的时间的时间差的结果

*/

double dd = [datenow timeIntervalSince1970] - [newdate timeIntervalSince1970];

double ss = 1;

NSString *timeString = nil;

if (dd/3600 < ss) {

timeString = [NSString stringWithFormat:@"%.0f", dd/60];

timeString = [NSString stringWithFormat:@"%@分钟前", timeString];

}

if (dd/3600 > ss && dd/86400 < ss) {

timeString = [NSString stringWithFormat:@"%.0f", dd/3600];

timeString = [NSString stringWithFormat:@"%@小时前", timeString];

}

if (dd/86400 > ss) {

timeString = [NSString stringWithFormat:@"%.0f", dd/86400];

timeString = [NSString stringWithFormat:@"%@天前", timeString];

}

NSLog(@"=====%@",timeString);

}

02. 获取当前月份的天数(传个时间进去,格式你自己定义如:@"2016-06-01 00:00")

- (NSInteger)getNumberOfDaysInMonth:(NSString *)dateString{

NSCalendar * calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];

NSDateFormatter *fd = [[NSDateFormatter alloc]init];

[fd setDateFormat:@"YYYY-MM-dd HH:mm"];

[fd setTimeZone:[NSTimeZone timeZoneWithAbbreviation:@"UTC"]];

// 这个日期就是传进来的日期转换成时间

NSDate *currentDate = [fd dateFromString:dateString];

NSRange range = [calendar rangeOfUnit:NSDayCalendarUnit

inUnit: NSMonthCalendarUnit

forDate:currentDate];

return range.length;

}

你可能感兴趣的:(iOS 玩转时间(NSDate)(持续更新))