NSDate--查询某天是星期几

2016-06-20  本文已影响655人  天亮説晚安
- (NSString*)weekdayStringFromDate:(NSString*)inputDateStr {
    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;
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    formatter.dateFormat = @"yyyy-MM-dd HH:mm:ss";//日期格式化类
    NSDate *inputDate = [formatter dateFromString:inputDateStr];//转化为NSDate时间
    NSDateComponents *theComponents = [calendar components:calendarUnit fromDate:inputDate];
    return [weekdays objectAtIndex:theComponents.weekday];
}

-(NSString *)compareDate:(NSString *)dateStr
{
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    formatter.dateFormat = @"yyyy-MM-dd HH:mm:ss";//日期格式化类
    NSDate * date = [formatter dateFromString:dateStr];//转化为NSDate时间
    NSTimeInterval secondsPerDay = 24 * 60 * 60;
    NSDate *today = [[NSDate alloc] init];
    NSDate *tomorrow, *yesterday;
    tomorrow = [today dateByAddingTimeInterval: secondsPerDay];
    yesterday = [today dateByAddingTimeInterval: -secondsPerDay];
    // 10 first characters of description is the calendar date:
    NSString * todayString = [[today description] substringToIndex:10];
    NSString * yesterdayString = [[yesterday description] substringToIndex:10];
    NSString * tomorrowString = [[tomorrow description] substringToIndex:10];
    NSString * dateString = [[date description] substringToIndex:10];
    if ([dateString isEqualToString:todayString])
    {
        return @"今天";
    } else if ([dateString isEqualToString:yesterdayString])
    {
        return @"昨天";
    }else if ([dateString isEqualToString:tomorrowString])
    {
        return @"明天";
    }
    else
    {
        return dateString;
    }
}

//比较两个时间
-(NSInteger)compareFirstTime:(NSString *)firstTime WithSecondTime:(NSString *)secondTime WithDateFormat:(NSString *)dateFormat
{
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:dateFormat];
    NSDate *dateA = [dateFormatter dateFromString:firstTime];
    NSDate *dateB = [dateFormatter dateFromString:secondTime];
    NSComparisonResult result = [dateA compare:dateB];
    if (result == NSOrderedDescending)
    {
        //NSLog(@"firstTime比 secondTime时间晚");
        return 1;
    }
    else if (result == NSOrderedAscending)
    {
        //NSLog(@"firstTime比 firstTime时间早");
        return -1;
    }
    else
    {
        //NSLog(@"两者时间是同一个时间");
        return 0;
    }
}

上一篇下一篇

猜你喜欢

热点阅读