IOS/objective-c:将unix时间戳字符串转换为NSDate格式



我试图获得NSDate格式的当前时间。我已经能够使Unix时间戳工作,但是,当我尝试使用我在SO上找到的答案转换和格式化时,我得到一个空结果。如果有人告诉我哪里做错了,我将不胜感激。

也会对以日期时间格式获得当前日期时间的任何更直接的方法感兴趣,即....比如2015-09-04 00:55:25 +0000

- (NSDate *) timeStampDate {
    //this returns time in string format
    NSString *string = [NSString stringWithFormat:@"%f",[[NSDate date] timeIntervalSince1970] * 1000];
    NSLog(@"string:%@",string);//this prints fine
    // Convert string to date object
    NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
    [dateFormat setDateFormat:@"yyyyMMdd"];
    NSDate *date = [dateFormat dateFromString:string];
    NSLog(@"date%@",date);//this prints null
    return date;
/* this would go in opposite direction
        [dateFormat setDateFormat:@"EEEE MMMM d, YYYY"];
    string = [dateFormat stringFromDate:date];
 */
}
-(NSDate*) timeStampDate {
    NSDate* currentDate = [NSDate date];
    return [NSDate dateWithTimeInterval:
        [[NSTimeZone defaultTimeZone] secondsFromGMTForDate: currentDate]
                          sinceDate: currentDate];
}

最新更新