获取当前日期(以毫秒为单位)

时间:2011-05-27 09:38:55

标签: objective-c cocoa-touch ios date time

任何人都可以告诉我如何以毫秒为单位获取当前日期吗?

12 个答案:

答案 0 :(得分:97)

有几种方法可以做到这一点,虽然我个人最喜欢的是:

CFAbsoluteTime timeInSeconds = CFAbsoluteTimeGetCurrent();

您可以阅读有关此方法的更多信息here。你也可以创建一个NSDate对象,并通过调用timeIntervalSince1970来获取时间,该seconds自1970年1月1日起返回{{3}}:

NSTimeInterval timeInSeconds = [[NSDate date] timeIntervalSince1970];

在斯威夫特:

let timeInSeconds: TimeInterval = Date().timeIntervalSince1970

答案 1 :(得分:59)

将NSTimeInterval直接转换为一个长时间溢出的对象,所以我不得不施展很长时间。

long long milliseconds = (long long)([[NSDate date] timeIntervalSince1970] * 1000.0);

结果是在Unix中的13位数时间戳。

答案 2 :(得分:10)

NSTimeInterval milisecondedDate = ([[NSDate date] timeIntervalSince1970] * 1000);

答案 3 :(得分:7)

extension NSDate {

    func toMillis() -> NSNumber {
        return NSNumber(longLong:Int64(timeIntervalSince1970 * 1000))
    }

    static func fromMillis(millis: NSNumber?) -> NSDate? {
        return millis.map() { number in NSDate(timeIntervalSince1970: Double(number) / 1000)}
    }

    static func currentTimeInMillis() -> NSNumber {
        return NSDate().toMillis()
    }
}

答案 4 :(得分:6)

你可以这样做:

long currentTime = (long)(NSTimeInterval)([[NSDate date] timeIntervalSince1970]);

这将返回一个毫秒的值,所以如果你将结果值乘以1000(如我的Eimantas建议的那样),你将溢出long类型,它将导致负值。

例如,如果我现在运行该代码,它将导致

currentTime = 1357234941

currentTime /seconds / minutes / hours / days = years
1357234941 / 60 / 60 / 24 / 365 = 43.037637652207

答案 5 :(得分:5)

@JavaZava你的解决方案很好,但是如果你想要一个13位长的值与Java或JavaScript(和其他语言)中的时间戳格式一致,请使用以下方法:

NSTimeInterval time = ([[NSDate date] timeIntervalSince1970]); // returned as a double
long digits = (long)time; // this is the first 10 digits
int decimalDigits = (int)(fmod(time, 1) * 1000); // this will get the 3 missing digits
long timestamp = (digits * 1000) + decimalDigits;

或(如果你需要一个字符串):

NSString *timestampString = [NSString stringWithFormat:@"%ld%d",digits ,decimalDigits];

答案 6 :(得分:2)

如前所述,   [[NSDate date] timeIntervalSince1970]返回NSTimeInterval,这是一个以秒为单位的持续时间,而不是毫秒。

您可以访问https://currentmillis.com/,了解如何使用您想要的语言。这是清单 -

ActionScript    (new Date()).time
C++ std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::system_clock::now().time_since_epoch()).count()
C#.NET  DateTimeOffset.UtcNow.ToUnixTimeMilliseconds()
Clojure (System/currentTimeMillis)
Excel / Google Sheets*  = (NOW() - CELL_WITH_TIMEZONE_OFFSET_IN_HOURS/24 - DATE(1970,1,1)) * 86400000
Go / Golang time.Now().UnixNano() / 1000000
Hive*   unix_timestamp() * 1000
Java / Groovy / Kotlin  System.currentTimeMillis()
Javascript  new Date().getTime()
MySQL*  UNIX_TIMESTAMP() * 1000
Objective-C (long long)([[NSDate date] timeIntervalSince1970] * 1000.0)
OCaml   (1000.0 *. Unix.gettimeofday ())
Oracle PL/SQL*  SELECT (SYSDATE - TO_DATE('01-01-1970 00:00:00', 'DD-MM-YYYY HH24:MI:SS')) * 24 * 60 * 60 * 1000 FROM DUAL
Perl    use Time::HiRes qw(gettimeofday); print gettimeofday;
PHP round(microtime(true) * 1000)
PostgreSQL  extract(epoch FROM now()) * 1000
Python  int(round(time.time() * 1000))
Qt  QDateTime::currentMSecsSinceEpoch()
R*  as.numeric(Sys.time()) * 1000
Ruby    (Time.now.to_f * 1000).floor
Scala   val timestamp: Long = System.currentTimeMillis
SQL Server  DATEDIFF(ms, '1970-01-01 00:00:00', GETUTCDATE())
SQLite* STRFTIME('%s', 'now') * 1000
Swift*  let currentTime = NSDate().timeIntervalSince1970 * 1000
VBScript / ASP  offsetInMillis = 60000 * GetTimeZoneOffset()
WScript.Echo DateDiff("s", "01/01/1970 00:00:00", Now()) * 1000 - offsetInMillis + Timer * 1000 mod 1000

对于目标C我做了类似下面的事情来打印它 -

long long mills = (long long)([[NSDate date] timeIntervalSince1970] * 1000.0);
 NSLog(@"Current date %lld", mills);

跳这有帮助。

答案 7 :(得分:1)

NSTimeInterval milisecondedDate值转换为nsstring,之后转换为int

答案 8 :(得分:0)

您可以使用以下方法获取当前日期(以毫秒为单位)。

[[NSDate date] timeIntervalSince1970];


double CurrentTime = CACurrentMediaTime(); 

来源: iPhone: How to get current milliseconds?

答案 9 :(得分:0)

- (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;
    }

答案 10 :(得分:0)

使用此选项以毫秒为单位获取时间(long)(NSTimeInterval)([[NSDate date] timeIntervalSince1970])

答案 11 :(得分:0)

日期延期可能是最好的解决方法。

extension NSDate {
    func msFromEpoch() -> Double {
        return self.timeIntervalSince1970 * 1000
    }
}