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

发布于 2024-11-10 05:18:49 字数 32 浏览 0 评论 0原文

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

Can any one give me an idea how to get the current date in milliseconds?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(12

用心笑 2024-11-17 05:18:50

@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];

@JavaZava your solution is good, but if you want to have a 13 digit long value to be consistent with the time stamp formatting in Java or JavaScript (and other languages) use this method:

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;

or (if you need a string):

NSString *timestampString = [NSString stringWithFormat:@"%ld%d",digits ,decimalDigits];
凉风有信 2024-11-17 05:18:50

正如前面提到的,
[[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

为了目标 CI 做了类似下面的事情来打印它 -

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

希望这会有所帮助。

As mentioned before,
[[NSDate date] timeIntervalSince1970] returns an NSTimeInterval, which is a duration in seconds, not milli-seconds.

You can visit https://currentmillis.com/ to see how you can get in the language you desire. Here is the list -

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

For objective C I did something like below to print it -

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

Hopw this helps.

忆离笙 2024-11-17 05:18:50

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

Cconvert NSTimeInterval milisecondedDate value to nsstring and after that convert into int.

迷雾森÷林ヴ 2024-11-17 05:18:50

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

[[NSDate date] timeIntervalSince1970];

double CurrentTime = CACurrentMediaTime(); 

来源:
iPhone:如何获取当前毫秒数?

You can use following methods to get current date in milliseconds.

[[NSDate date] timeIntervalSince1970];

OR

double CurrentTime = CACurrentMediaTime(); 

Source:
iPhone: How to get current milliseconds?

空‖城人不在 2024-11-17 05:18:50
- (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;
    }
- (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;
    }
蝶舞 2024-11-17 05:18:50

使用它来获取以毫秒为单位的时间(long)(NSTimeInterval)([[NSDate date] timeIntervalSince1970])

Use this to get the time in milliseconds (long)(NSTimeInterval)([[NSDate date] timeIntervalSince1970]).

时光沙漏 2024-11-17 05:18:50

延长日期可能是最好的办法。

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

An extension on date is probably the best way to about it.

extension NSDate {
    func msFromEpoch() -> Double {
        return self.timeIntervalSince1970 * 1000
    }
}
温柔少女心 2024-11-17 05:18:49

有多种方法可以做到这一点,尽管我个人最喜欢的是:

CFAbsoluteTime timeInSeconds = CFAbsoluteTimeGetCurrent();

您可以阅读有关此方法的更多信息 这里。您还可以创建 NSDate 对象并通过调用 timeIntervalSince1970 返回 自 1970 年 1 月 1 日以来:

NSTimeInterval timeInSeconds = [[NSDate date] timeIntervalSince1970];

在 Swift 中:

let timeInSeconds: TimeInterval = Date().timeIntervalSince1970

There are several ways of doing this, although my personal favorite is:

CFAbsoluteTime timeInSeconds = CFAbsoluteTimeGetCurrent();

You can read more about this method here. You can also create a NSDate object and get time by calling timeIntervalSince1970 which returns the seconds since 1/1/1970:

NSTimeInterval timeInSeconds = [[NSDate date] timeIntervalSince1970];

And in Swift:

let timeInSeconds: TimeInterval = Date().timeIntervalSince1970
ぶ宁プ宁ぶ 2024-11-17 05:18:49

将 NSTimeInterval 直接转换为 long 对我来说会溢出,因此我必须转换为 long long。

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

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

Casting the NSTimeInterval directly to a long overflowed for me, so instead I had to cast to a long long.

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

The result is a 13 digit timestamp as in Unix.

眼眸印温柔 2024-11-17 05:18:49
NSTimeInterval milisecondedDate = ([[NSDate date] timeIntervalSince1970] * 1000);
NSTimeInterval milisecondedDate = ([[NSDate date] timeIntervalSince1970] * 1000);
家住魔仙堡 2024-11-17 05:18:49

你可以这样做:

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

You can just do this:

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

this will return a value en milliseconds, so if you multiply the resulting value by 1000 (as suggested my Eimantas) you'll overflow the long type and it'll result in a negative value.

For example, if I run that code right now, it'll result in

currentTime = 1357234941

and

currentTime /seconds / minutes / hours / days = years
1357234941 / 60 / 60 / 24 / 365 = 43.037637652207
红ご颜醉 2024-11-17 05:18:49
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()
    }
}
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()
    }
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文