NSDate和NSDateFormatter 相关应用代码示例

此方法用来计算当前时间与目标时间的先后顺序:


-(NSDate *)calculateTimeWithCurrentTime:(NSDate *)currentDate{
//将当前时间转为本地时区
NSDate * currentLocalDate = [self localDateFromDate:currentDate];
NSLog(@"currentDate--->%@",currentLocalDate);
//设置目标时间为当天15:30
NSString *dateStr = [NSString stringWithFormat:@"%@",currentLocalDate];
NSString *dateString = [dateStr substringToIndex:11];
NSString *targetDateStr = [NSString stringWithFormat:@"%@15:30:00",dateString];
NSDateFormatter *formatter001 = [[NSDateFormatter alloc] init];
[formatter001 setDateFormat:@"YYYY-MM-dd HH:mm:ss"];
NSDate * targetDate = [formatter001 dateFromString:targetDateStr];
//将目标时间转为本地时区
targetDate = [self localDateFromDate:targetDate];
NSLog(@"targetDate--->%@",targetDate);
//比较当前时间和目标时间
NSComparisonResult result = [currentLocalDate compare:targetDate];
NSLog(@"result--->%d",result);
//获取当前日期是星期几
NSString *weekDay = [self weekdayStringFromDate:currentDate];
NSLog(@"weekDay--->%@",weekDay);
//计算收益时间
NSDate *calDate;
if ([weekDay isEqualToString:@"周一"] || [weekDay isEqualToString:@"周二"] || [weekDay isEqualToString:@"周三"] ) {
//升序
if (result == NSOrderedAscending) {
NSLog(@"15:30之前");
calDate = [currentDate dateByAddingTimeInterval:aDay];
}
else{
NSLog(@"15:30之后");
calDate = [currentDate dateByAddingTimeInterval:2*aDay];
}
}
else if ([weekDay isEqualToString:@"周四"]){
//升序
if (result == NSOrderedAscending) {
calDate = [currentDate dateByAddingTimeInterval:aDay];
}
else{
calDate = [currentDate dateByAddingTimeInterval:4*aDay];
}
}
else if ([weekDay isEqualToString:@"周五"]){
//升序
if (result == NSOrderedAscending) {
calDate = [currentDate dateByAddingTimeInterval:3*aDay];
}
else{
calDate = [currentDate dateByAddingTimeInterval:4*aDay];
}
}
else if ([weekDay isEqualToString:@"周六"]){
calDate = [currentDate dateByAddingTimeInterval:3*aDay];
}
else if ([weekDay isEqualToString:@"周日"]){
calDate = [currentDate dateByAddingTimeInterval:2*aDay];
}
calDate = [self localDateFromDate:calDate];
return calDate;
}

将时区转为当前时区

- (NSDate *)localDateFromDate:(NSDate *)date{
//获取系统时区
NSTimeZone *zone = [NSTimeZone systemTimeZone];
//时间间隔
NSInteger interval = [zone secondsFromGMTForDate: date];
//得到当前时间
NSDate *localeDate = [date dateByAddingTimeInterval: interval];
return localeDate;
}

判断当天是星期几:

- (NSString*)weekdayStringFromDate:(NSDate*)inputDate {
NSArray *weekdays = [NSArray arrayWithObjects: [NSNull null],@"周日", @"周一", @"周二", @"周三", @"周四", @"周五", @"周六", nil];
NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSCalendarIdentifierGregorian];
NSTimeZone *timeZone = [[NSTimeZone alloc] initWithName:@"Asia/Shanghai"];
[calendar setTimeZone: timeZone];
NSCalendarUnit calendarUnit = NSCalendarUnitWeekday;
NSDateComponents *theComponents = [calendar components:calendarUnit fromDate:inputDate];
return [weekdays objectAtIndex:theComponents.weekday];
}
上一篇:虚拟机安装CentOS,网络配置


下一篇:个人博客网站