2016-04-14 16 views
0

Ich muss ein NSDate in C# Ticks umwandeln.Swift: NSDate in C# Ticks umwandeln

DateTime.ticks konvertiert Datum Zecken von 1 0001.

ab Januar Wie kann ich das tun? Vielen Dank im Voraus.

+0

'timeIntervalSinceReferenceDate' Gibt das Intervall zwischen dem Zeitpunkt Objekt und 00.00.00 UTC am 1. Januar 2001 (read-only) – zcui93

+0

Ihre Frage ist _really_ vauge und unklar. Kannst du bitte ** mehr ** spezifisch sein? A [mcve] wäre nett .. –

Antwort

2

Ich habe diesen Code irgendwo ausgeliehen, also bin ich kein Autor. Hier geht es:

@implementation NSDate (Ticks) 

    - (long long) ticks 
    { 
     double tickFactor = 10000000; 
     long long tickValue = (long long)floor([self timeIntervalSince1970] * tickFactor) + 621355968000000000LL; 
     return tickValue; 
    } 

    + (NSDate*) dateWithTicks:(long long)ticks 
    { 
     double tickFactor = 10000000; 
     double seconds = (ticks - 621355968000000000LL)/tickFactor; 
     return [NSDate dateWithTimeIntervalSince1970:seconds]; 
    } 

    @end 
1

Die OP getaggt seine Frage mit Swift, so ist hier eine alternative Antwort, obwohl es im Grunde die gleichen wie Nikolay geschrieben hat. Diese Version bietet jedoch Unterstützung für die Zuordnung von DateTime.MinValue und DateTime.MaxValue zu/from Date.distantPast und Date.distantFuture.

private static let CTicksAt1970 : Int64 = 621_355_968_000_000_000 
    private static let CTicksPerSecond : Double = 10_000_000 

    private static let CTicksMinValue : Int64 = 0 
    private static let CTicksMaxValue : Int64 = 3_155_378_975_999_999_999 


     // Method to create a Swift Date struct to reflect the instant in time specified by a "ticks" 
     // value, as used in .Net DateTime structs. 
     internal static func swiftDateFromDotNetTicks(_ dotNetTicks : Int64) -> Date { 

      if dotNetTicks == CTicksMinValue { 
      return Date.distantPast 
      } 

      if dotNetTicks == CTicksMaxValue { 
      return Date.distantFuture 
      } 

      let dateSeconds = Double(dotNetTicks - CTicksAt1970)/CTicksPerSecond 
      return Date(timeIntervalSince1970: dateSeconds) 
     } 


     // Method to "convert" a Swift Date struct to the corresponding "ticks" value, as used in .Net 
     // DateTime structs. 
     internal static func dotNetTicksFromSwiftDate(_ swiftDate : Date) -> Int64 { 

      if swiftDate == Date.distantPast { 
      return CTicksMinValue 
      } 

      if swiftDate == Date.distantFuture { 
      return CTicksMaxValue 
      } 

      let dateSeconds = Double(swiftDate.timeIntervalSince1970) 
      let ticksSince1970 = Int64(round(dateSeconds * CTicksPerSecond)) 
      return CTicksAt1970 + ticksSince1970 
     } 
Verwandte Themen