iOS时间类型转换

时间格式转换

//model.birthday = Birthday = “1980-01-01″;

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

[formatter setDateFormat:@”yyyy-MM-dd”];

NSDate * date = [formatter dateFromString:model.birthday];

[formatter setDateFormat:@”yyyy年MM月dd日”];

NSString * birthdayStr = [formatter stringFromDate:date];

NSLog(@”%@”,birthdayStr);//1980年01月01日

//获取系统当前时间

-(NSString *)getCurrentDateStr

{

    //获取系统当前时间

    NSDate *currentDate = [NSDate date];

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

    [dateFormatter setDateFormat:@”yyyy-MM-dd HH:mm:ss”];

    NSString *dateString = [dateFormatter stringFromDate:currentDate];

    return dateString;

}

//转换成年月日格式的日期

    

#pragma mark –时间转换成年月日

+(NSString *)dateStrFormString:(NSString *)string

{

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

    [dateFormatter setDateFormat:@”yyyy-MM-dd HH:mm:ss”];

    NSDate *date = [dateFormatter dateFromString:string];

    [dateFormatter setDateFormat:@”yyyyMMdd HH:mm:ss”];

    NSString *dateString = [dateFormatter stringFromDate:date];

    return dateString;

}

//获取日期的年、月、日、时、分、秒

+ (NSDateComponents*)dateFromeString:(NSString*)dateStr{

    NSString* formatter = @”yyyy-MM-dd HH:mm:ss”;

    return [Factory dateFromeString:dateStr withFormatter:formatter];

}

/**

*  从字符串中获取时间

*

*  @param dateStr   时间字符串

*  @param formatter 待设置的解析字符串的格式

*

*  @return 返回系统时间model,使用如下:NSInteger hour = [dateComponent hour];

*/

+ (NSDateComponents*)dateFromeString:(NSString *)dateStr withFormatter:(NSString *)formatter{

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

    [mdateformatter setDateFormat:formatter];

    [mdateformatter setTimeZone:[NSTimeZone timeZoneWithAbbreviation:@”CCD +08:00″]];

    NSDate * date = [mdateformatter dateFromString:dateStr];

    NSCalendar * calendar = [NSCalendar calendarWithIdentifier:NSCalendarIdentifierGregorian];

    unsigned int unitFlags = NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit | NSHourCalendarUnit;

    NSDateComponents * dateComponent = [calendar components:unitFlags fromDate:date];

    return dateComponent;

}

 

分享到: 更多
Separator image Posted in IOS.