iOS 获取年月日和星期几

/**

获取年月日,星期几

**/


+ (NSString *)currentDate;

+ (NSString *)currentDate {

    NSString *time;

    NSDate *date =[NSDate date];

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

   [formatter setDateFormat:@"yyyy"];

   NSInteger currentYear=[[formatter stringFromDate:date] integerValue];

   [formatter setDateFormat:@"MM"];

   NSInteger currentMonth=[[formatter stringFromDate:date]integerValue];

   [formatter setDateFormat:@"dd"];

   NSInteger currentDay=[[formatter stringFromDate:date] integerValue];

   NSString *day = [NSString stringWithFormat:@"%ld",currentDay];

   NSString *month = [NSString stringWithFormat:@"%ld",currentMonth];

   NSString *week = [NSString weekdayStringFromDate:date];

   if (currentMonth < 10) {

     month = [NSString stringWithFormat:@"0%@",month];

    }

  if (currentDay < 10) {

    day = [NSString stringWithFormat:@"0%@",day];

  }

   time = [NSString stringWithFormat:@"%ld.%@.%@ %@",currentYear,month,day,week];

   return time;

}

+ (NSString*)weekdayStringFromDate:(NSDate*)inputDate {

NSArray *weekdays = [NSArray arrayWithObjects: [NSNull null], @"星期日", @"星期一", @"星期二", @"星期三", @"星期四", @"星期五", @"星期六", nil];

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

NSTimeZone *timeZone = [[NSTimeZone alloc] initWithName:@"Asia/Shanghai"];

[calendar setTimeZone: timeZone];

NSCalendarUnit calendarUnit = NSWeekdayCalendarUnit;

NSDateComponents *theComponents = [calendar components:calendarUnit fromDate:inputDate];

return [weekdays objectAtIndex:theComponents.weekday];

}

你可能感兴趣的:(iOS 获取年月日和星期几)