首页 > 其他 > 详细

判断日期是昨天,今天,明天,后天,其他的显示星期

时间:2014-02-08 16:19:33      阅读:569      评论:0      收藏:0      [点我收藏+]
bubuko.com,布布扣
DayClass.h
#import <Foundation/Foundation.h>

@interface DayClass : NSObject

- (NSString *)dateToStr:(NSDate *)date;

@end

DayClass.m
#import "DayClass.h"

enum{
    Sun = 1,
    Mon,
    Tue,
    Wed,
    Thu,
    Fri,
    Sat
};

@implementation DayClass


- (NSString *)dateToStr:(NSDate *)date
{
    NSString *flagString = nil;
    
    // 当前日期
    int currentDate = [self getIntegerFromDate:[NSDate date]];
    // 目标日期
    int tar = [self getIntegerFromDate:date];
    // 时间差
    int diff = tar - currentDate;
    
    if ( diff < 3 && diff >= 0)
    {
        switch (diff)
        {
            case 0:
                flagString = @"今天";
                break;
            case 1:
                flagString = @"明天";
                break;
            case 2:
                flagString = @"后天";
                break;
            default:
                break;
        }
    }
    else if (diff == -1)
    {
        flagString = @"昨天";
    }
    else
    {
        NSCalendar* clendar = [ [ NSCalendar alloc ] initWithCalendarIdentifier:NSChineseCalendar];
        NSUInteger unitFlags = NSWeekdayCalendarUnit;
        NSDateComponents *cps = [clendar components:unitFlags fromDate:date ];
        switch ([cps weekday]) {
            case Sun:
                flagString = @"星期天";
                break;
            case Mon:
                flagString = @"星期一";
                break;
            case Tue:
                flagString = @"星期二";
                break;
            case Wed:
                flagString = @"星期三";
                break;
            case Thu:
                flagString = @"星期四";
                break;
            case Fri:
                flagString = @"星期五";
                break;
            case Sat:
                flagString = @"星期六";
                break;
            default:
                break;
        }
    }
    
    return flagString ;
}

- (int)getIntegerFromDate:(NSDate *)date
{
    NSDateFormatter *formatter = [[NSDateFormatter alloc]init];
    [formatter setDateFormat:@"yyyyMMdd"];
    NSString *todayStr = [formatter stringFromDate:date];
    int presentDay = [todayStr intValue];
    return presentDay;
}

@end

// 使用
  NSString* string = @"20140211";
  NSDateFormatter *inputFormatter = [[NSDateFormatter alloc] init];
  [inputFormatter setDateFormat:@"yyyyMMdd"];
  NSDate* inputDate = [inputFormatter dateFromString:string];
        
  DayClass *day = [[DayClass alloc]init];
  NSLog(@"%@",[day dateToStr:inputDate]);
bubuko.com,布布扣

判断日期是昨天,今天,明天,后天,其他的显示星期

原文:http://www.cnblogs.com/joesen/p/3540207.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!