2016-04-14 79 views
0

我需要將NSDate轉換爲C#ticks。Swift:將NSDate轉換爲c#ticks

DateTime.ticks轉換日期從1月1日0001

開始我如何能做到這一點蜱? 在此先感謝。

+0

'timeIntervalSinceReferenceDate'返回2001年1月1日的日期對象和UTC 00:00:00之間的時間間隔(只讀) – zcui93

+0

你的問題是_really_ vauge不清。你可以請**更多**具體? [mcve]會很好.. –

回答

2

我借用了這段代碼,所以我不是作者。這裏有雲:

@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標記他與斯威夫特的問題,所以這裏是一個備選答案,但它基本上是一樣的尼古拉已經發布。但是,此版本添加了將DateTime.MinValue和DateTime.MaxValue映射到Date.distantPast和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 
     }