2016-04-14 18 views
0

NSDate'i C# kenelerine dönüştürmem gerekiyor.Swift: NSDate'i C# ticks'a dönüştürün

DateTime.ticks bunu yapabilirim nasıl 0001.

1 Ocak itibaren tık tarihini dönüştürür? Şimdiden teşekkürler.

+0

'timeIntervalSinceReferenceDate' 1 Ocak 2001 tarih nesne ve 00:00:00 UTC arasındaki aralığı döndürür (salt okunur) – zcui93

+0

Sorunuz _really_ vauge ve belirsizdir. ** daha fazla ** özel olabilir misiniz? Bir [mcve] iyi olurdu .. –

cevap

2

Bu kodu bir yerden ödünç aldım, bu yüzden bir yazar değilim. işte,

@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

OP Swift ile yaptığı sorusunu etiketli Nikolay gönderdi olarak temelde aynı olmasına rağmen, alternatif bir cevap var: İşte gider. Ancak, bu sürüm, Date.dimePat ve Date.distantFuture/DateDimePat ve DateTime.MaxValue eşleme için destek ekler.

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 
     }