iOS 时间 时间戳

时间在线转化:http://tool.chinaz.com/Tools/unixtime.aspx

1.日期格式转字符串

//日期格式转字符串
- (NSString *)dateToString:(NSDate *)date withDateFormat:(NSString *)format
{

    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    
    [dateFormatter setDateFormat:format];
    
    NSString *strDate = [dateFormatter stringFromDate:date];
    
    return strDate;
}

2.//字符串转日期格式

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

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

3.//date字符串转时间戳

//date字符串转时间戳
- (NSInteger)dateStrToTimeInterval:(NSString *)dataStr withDateFormat:(NSString *)format
{
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    
    [formatter setDateStyle:NSDateFormatterMediumStyle];
    
    [formatter setTimeStyle:NSDateFormatterShortStyle];
    
    [formatter setDateFormat:format];
    
    NSTimeZone* timeZone = [NSTimeZone timeZoneWithName:@"Asia/Beijing"];
    
    [formatter setTimeZone:timeZone];
    
    NSDate* date = [formatter dateFromString:dataStr];
    
    //时间转时间戳的方法:
    
    NSInteger timeSp = [[NSNumber numberWithDouble:[date timeIntervalSince1970]] integerValue];
    
    return timeSp;
}

举例:

    
    NSDate *nowDate = [NSDate date];
    
    NSLog(@"----初始日期:%@-----",nowDate);

    NSString *str1 = [self dateToString:nowDate withDateFormat:@"yyyy-MM-dd HH:mm:ss"];

    NSLog(@"----当前日期:%@-----",str1);
    
    NSDate *date = [self stringToDate:str1 withDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    
    NSLog(@"----字符日期:%@-----",date);

    NSInteger inter = [self dateStrToTimeInterval:str1 withDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    
    NSLog(@"-----时间戳:%ld-----",inter);

你可能感兴趣的:(iOS 时间 时间戳)