简体   繁体   English

如何将NSDate转换为unix时间戳iphone sdk?

[英]How to convert NSDate into unix timestamp iphone sdk?

How to convert an NSDate into Unix timestamp? 如何将NSDate转换为Unix时间戳? I've read many posts which do the reverse. 我读了很多相反的帖子。 But I'm not finding anything related to my question. 但我找不到任何与我的问题相关的内容。

我相信这是你正在寻找的NSDate的选择器:

- (NSTimeInterval)timeIntervalSince1970

A Unix timestamp is the number of seconds since 00:00:00 UTC January 1, 1970. It's represented by the type time_t , which is usually a signed 32-bit integer type (long or int). Unix时间戳是自1970年1月1日00:00:00 UTC以来的秒数。它由time_t类型表示,它通常是带符号的32位整数类型(long或int)。

iOS provides -(NSTimeInterval)timeIntervalSince1970 for NSDate objects which returns the number of seconds since 00:00:00 GMT January 1, 1970. NSTimeInterval is a double floating point type so you get the seconds and fractions of a second. iOS为NSDate对象提供了- (NSTimeInterval)timeIntervalSince1970 ,它返回自1970年1月1日格林威治标准时间00:00:00以来的秒数.NSTimeInterval是一个双浮点类型,因此您可以获得秒和分数秒。

Since they both have the same reference (midnight 1Jan1970 UTC) and are both in seconds the conversion is easy, convert the NSTimeInterval to a time_t, rounding or truncating depending on your needs: 由于它们都具有相同的引用(午夜1Jan1970 UTC)并且都在几秒内转换很容易,将NSTimeInterval转换为time_t,根据您的需要进行舍入或截断:

time_t unixTime = (time_t) [[NSDate date] timeIntervalSince1970];

您可以通过以下方式从日期创建unix时间戳日期:

NSTimeInterval timestamp = [[NSDate date] timeIntervalSince1970];
- (void)GetCurrentTimeStamp
    {
        NSDateFormatter *objDateformat = [[NSDateFormatter alloc] init];
        [objDateformat setDateFormat:@"yyyy-MM-dd"];
        NSString    *strTime = [objDateformat stringFromDate:[NSDate date]];
        NSString    *strUTCTime = [self GetUTCDateTimeFromLocalTime:strTime];//You can pass your date but be carefull about your date format of NSDateFormatter.
        NSDate *objUTCDate  = [objDateformat dateFromString:strUTCTime];
        long long milliseconds = (long long)([objUTCDate timeIntervalSince1970] * 1000.0);

        NSString *strTimeStamp = [Nsstring stringwithformat:@"%lld",milliseconds];
        NSLog(@"The Timestamp is = %@",strTimestamp);
    }

 - (NSString *) GetUTCDateTimeFromLocalTime:(NSString *)IN_strLocalTime
    {
        NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
        [dateFormatter setDateFormat:@"yyyy-MM-dd"];
        NSDate  *objDate    = [dateFormatter dateFromString:IN_strLocalTime];
        [dateFormatter setTimeZone:[NSTimeZone timeZoneWithAbbreviation:@"UTC"]];
        NSString *strDateTime   = [dateFormatter stringFromDate:objDate];
        return strDateTime;
    }

NOTE :- The Timestamp must be in UTC Zone, So I convert our local Time to UTC Time. 注意: - 时间戳必须是UTC区域,因此我将本地时间转换为UTC时间。

Swift 迅速

Updated for Swift 3 针对Swift 3进行了更新

// current date and time
let someDate = Date()

// time interval since 1970
let myTimeStamp = someDate.timeIntervalSince1970

Notes 笔记

  • timeIntervalSince1970 returns TimeInterval , which is a typealias for Double . timeIntervalSince1970返回TimeInterval ,它是Double
  • If you wanted to go the other way you could do the following: 如果你想走另一条路,你可以做以下事情:

     let myDate = Date(timeIntervalSince1970: myTimeStamp) 

我首选的方法是:

NSDate.date.timeIntervalSince1970;

If you want to store these time in a database or send it over the server...best is to use Unix timestamps. 如果要将这些时间存储在数据库中或通过服务器发送...最好是使用Unix时间戳。 Here's a little snippet to get that: 这是一个小小的代码片段:

+ (NSTimeInterval)getUTCFormateDate{

    NSDateComponents *comps = [[NSCalendar currentCalendar] 
                               components:NSDayCalendarUnit | NSYearCalendarUnit | NSMonthCalendarUnit 
                               fromDate:[NSDate date]];
    [comps setHour:0];
    [comps setMinute:0];    
    [comps setSecond:[[NSTimeZone systemTimeZone] secondsFromGMT]];

    return [[[NSCalendar currentCalendar] dateFromComponents:comps] timeIntervalSince1970];  
}

As per @kexik's suggestion using the UNIX time function as below : 根据@kexik的建议使用UNIX时间函数如下:

  time_t result = time(NULL);
  NSLog([NSString stringWithFormat:@"The current Unix epoch time is %d",(int)result]);

.As per my experience - don't use timeIntervalSince1970 , it gives epoch timestamp - number of seconds you are behind GMT. 根据我的经验 - 不要使用timeIntervalSince1970,它给出了纪元时间戳 - 你在GMT后面的秒数。

There used to be a bug with [[NSDate date]timeIntervalSince1970] , it used to add/subtract time based on the timezone of the phone but it seems to be resolved now. 曾经有[[NSDate date] timeIntervalSince1970]的错误,它用于根据手机的时区添加/减去时间,但现在似乎已经解决了。

 [NSString stringWithFormat: @"first unixtime is %ld",message,(long)[[NSDate date] timeIntervalSince1970]];

 [NSString stringWithFormat: @"second unixtime is %ld",message,[[NSDate date] timeIntervalSince1970]];

 [NSString stringWithFormat: @"third unixtime is %.0f",message,[[NSDate date] timeIntervalSince1970]]; 

first unixtime 1532278070 第一次unixtime 1532278070

second unixtime 1532278070.461380 第二次unixtime 1532278070.461380

third unixtime 1532278070 第三次unixtime 1532278070

If you need time stamp as a string. 如果您需要时间戳作为字符串。

time_t result = time(NULL);                
NSString *timeStampString = [@(result) stringValue];

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM