iOS 日期与字符串格式互转

前言

1、解决日期转字符串格式;
2、解决字符串转日期格式;
3、解决时区差;

代码如下:

#import "ViewController.h"

@interface ViewController ()

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];

    NSDate *nowDate = [NSDate date];
    NSString *str = [self dateToString:nowDate withDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    NSLog(@"%@",str);

    NSDate *newdate = [self stringToDate:@"2016-01-18 15:13:12" withDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    NSLog(@"%@",newdate);

}

//日期格式转字符串
- (NSString *)dateToString:(NSDate *)date withDateFormat:(NSString *)format
{
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:format];
    NSString *strDate = [dateFormatter stringFromDate:date];
    return strDate;
}

//字符串转日期格式
- (NSDate *)stringToDate:(NSString *)dateString withDateFormat:(NSString *)format
{
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:format];

    NSDate *date = [dateFormatter dateFromString:dateString];
    return [self worldTimeToChina:date];
}

//将世界时间转化为中国区时间
- (NSDate *)worldTimeToChinaTime:(NSDate *)date
{
    NSTimeZone *timeZone = [NSTimeZone systemTimeZone];
    NSInteger interval = [timeZone secondsFromGMTForDate:date];
    NSDate *localeDate = [date  dateByAddingTimeInterval:interval];
    return localeDate;
}

@end

你可能感兴趣的:(ios,NSDate)