Obtener la fecha actual en milisegundos


Respuestas:


103

Hay varias formas de hacer esto, aunque mi favorita personal es:

CFAbsoluteTime timeInSeconds = CFAbsoluteTimeGetCurrent();

Puedes leer más sobre este método aquí . También puede crear un objeto NSDate y obtener la hora llamando a timeIntervalSince1970, que devuelve los segundos desde el 1/1/1970:

NSTimeInterval timeInSeconds = [[NSDate date] timeIntervalSince1970];

Y en Swift:

let timeInSeconds: TimeInterval = Date().timeIntervalSince1970

4
estoy intentando tis siguiente código NSTimeInterval milisecondedDate = ([[NSDate fecha] timeIntervalSince1970] * 1000); NSLog (@ "didReceiveResponse ----% d", milisecondedDate);
— siva

2
El problema está en la declaración NSLog. NSTimeInterval es un tipo doble definido. Por tanto, debería utilizar% f en lugar de% d.
— Pawel

55
[[NSDate date] timeIntervalSince1970] devuelve un NSTimeInterval, que es una duración en segundos, no en milisegundos.
— Erik van der Neut

12
Tenga en cuenta que CFAbsoluteTimeGetCurrent()devuelve el tiempo relativo a la fecha de referencia Jan 1 2001 00:00:00 GMT. No es que se haya dado una fecha de referencia en la pregunta, pero tenga en cuenta que esta no es una marca de tiempo de UNIX.
— nyi

2
[[NSDate date] timeIntervalSince1970] devuelve el tiempo en segundos y no en milisegundos.
— SAPLogix

61

Lanzar el NSTimeInterval directamente a un largo se desbordó para mí, así que en su lugar tuve que lanzar a un largo.

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

El resultado es una marca de tiempo de 13 dígitos como en Unix.


4
Esto no devolverá los milisegundos reales porque timeIntervalSince1970 devuelve el intervalo en segundos, por lo que no tendremos la precisión de milisegundos deseada.
— Danpe

9
El timeIntervalSince1970 método devuelve los segundos en el número entero, sin embargo, doubletambién incluye la fracción de segundo que se puede convertir aritméticamente a milisegundos. Por lo tanto, la multiplicación por 1000.
— wileymab

@wileymap Sí, tienes razón. Lo descubrí más tarde
— Danpe

2
long long? este idioma es tan extraño
— user924

@ user924 No podría estar más de acuerdo. Por eso dejé de escribirlo. ;)
— wileymab

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

estoy intentando tis siguiente código NSTimeInterval milisecondedDate = ([[NSDate fecha] timeIntervalSince1970] * 1000); NSLog (@ "didReceiveResponse ----% d", milisecondedDate); - pero muestra el valor en val negativo - como ResponseTIME ---- 556610175 ResponseTIME ---- -1548754395
— siva

1
intente usar% f marcador de posición en lugar de% d. Si eso no ayuda, elimine la multiplicación por 1000
— Eimantas

@ Eimantas, cuando trato de usar% f ... Estoy obteniendo el tiempo como Sigue el tiempo de respuesta = 1306494959011.239014 Tiempo de respuesta = 1306494910724.744141 Si es ms, entonces el tiempo anterior es más de una hora.
— siva

La fecha actual es un intervalo de tiempo en segundos desde 1970. No mencionaste nada sobre la fecha de referencia.
— Eimantas

Tomaré solo el intervalo de tiempo de fecha actual
— siva

8
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()
    }
}

7

Puedes simplemente hacer esto:

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

esto devolverá un valor en milisegundos, por lo que si multiplica el valor resultante por 1000 (como sugirió mi Eimantas), desbordará el tipo largo y dará como resultado un valor negativo.

Por ejemplo, si ejecuto ese código ahora mismo, resultará en

currentTime = 1357234941

y

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

5

@JavaZava, su solución es buena, pero si desea tener un valor de 13 dígitos para ser coherente con el formato de la marca de tiempo en Java o JavaScript (y otros lenguajes), utilice este método:

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;

o (si necesita una cadena):

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

NSString * timestampString = [NSString stringWithFormat: @ "% ld% 03d", dígitos, decimalDigits]; es correcto en realidad. En su caso, si el valor decimalDigits es menor que 100 producirá un resultado incorrecto.
— PANKAJ VERMA

4

Como se mencionó anteriormente, [[NSDate date] timeIntervalSince1970] devuelve un NSTimeInterval, que es una duración en segundos, no milisegundos.

Puede visitar https://currentmillis.com/ para ver cómo puede obtener el idioma que desee. Aquí está la lista -

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

Para el objetivo, CI hizo algo como a continuación para imprimirlo:

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

Hopw esto ayuda.


1

Cconvertir NSTimeInterval milisecondedDatevalor ay nsstringdespués convertir en int.



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

0

Use esto para obtener el tiempo en milisegundos (long)(NSTimeInterval)([[NSDate date] timeIntervalSince1970]).


0

Una extensión de la fecha es probablemente la mejor manera de hacerlo.

extension NSDate {
    func msFromEpoch() -> Double {
        return self.timeIntervalSince1970 * 1000
    }
}
Al usar nuestro sitio, usted reconoce que ha leído y comprende nuestra Política de Cookies y Política de Privacidad.
Licensed under cc by-sa 3.0 with attribution required.