代碼:
代碼:
#import "RootViewController.h"
@interface RootViewController ()
@end
@implementation RootViewController
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
// Custom initialization
}
return self;
}
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view.
//獲得指定日期的格式
NSLog(@"---%@----",[self changeTheDate:@"2013-04-18" ByDateType:@"yyyy-M-dd"]);
//星期幾
NSLog(@"---%@---",[self getTheWeekDay:@"2013-04-18"]);
//一年的第幾周,每周的第幾天,比較兩天是不是同一個星期
NSDate* today = [NSDate date];
NSLog(@"--%ld---",(long)[self didWeekOfYear:today]);
NSLog(@"---%ld---",(long)[self didWeekDay:today]);
NSLog(@"---%ld---",(long)[self didSameWeek:today date:today]);
}
#pragma -mark -獲得指定日期的格式
/*獲得指定的日期格式
paramDate:日期的字元串表示:“2013-04-18”
paramDateType:要轉化的日期格式:“yyyy-M-dd”
*/
- (NSString *)changeTheDate:(NSString *)paramDate ByDateType:(NSString *)paramDateType{
// 將日期轉化為需要的格式 yyyy-MM-dd 轉化為 yyyy-M-dd
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc]init];
[dateFormatter setDateFormat:@"yyyy-MM-dd"];
NSDate *tempDate = [dateFormatter dateFromString:paramDate];
[dateFormatter setDateFormat:paramDateType];
NSString *theDate= [dateFormatter stringFromDate:tempDate];
NSString *result=[[NSString alloc] initWithString:theDate] ;
return result;
}
#pragma -mark -星期幾
/*星期幾*/
- (NSString *)getTheWeekDay:(NSString *)paramDate{
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc]init];
[dateFormatter setDateFormat:@"yyyy-M-dd"];
NSDate *theDate= [dateFormatter dateFromString:paramDate];
NSString *result=nil;
NSInteger theWeek=[self didWeekDay:theDate];
switch (theWeek) {
case 1:
result=@"星期日";
break;
case 2:
result=@"星期一";
break;
case 3:
result=@"星期二";
break;
case 4:
result=@"星期三";
break;
case 5:
result=@"星期四";
break;
case 6:
result=@"星期五";
break;
case 7:
result=@"星期六";
break;
default:
break;
}
return result;
}
#pragma -mark -每周的第幾天
//取當前時間是星期幾
- (NSInteger) didWeekDay:(NSDate*)date
{
NSCalendar *gregorian = [[NSCalendar alloc]
initWithCalendarIdentifier:NSGregorianCalendar];
NSDateComponents *weekdayComponents = [gregorian components:(NSDayCalendarUnit | NSWeekdayCalendarUnit) fromDate:date];
NSInteger tempweekday = [weekdayComponents weekday];
return tempweekday;
}
#pragma -mark -每年的第幾周
//取當前時間是每年中的第幾周
- (NSInteger) didWeekOfYear:(NSDate*)date
{
NSInteger unitFlags = NSWeekOfYearCalendarUnit;
NSCalendar *gregorian = [NSCalendar currentCalendar];
NSDateComponents *weekdayComponents = [gregorian components:unitFlags fromDate:date];
NSInteger weekOfYear = [weekdayComponents weekOfYear];
return weekOfYear;
}
#pragma -mark -判斷是不是一個星期
//判斷是不是同一個星期
- (BOOL) didSameWeek:(NSDate*)date1 date:(NSDate*)date2
{
NSInteger week1 = [self didWeekOfYear:date1];
NSInteger week2 = [self didWeekOfYear:date2];
return week1 == week2;
}
@end