将.NET DateTime.Ticks属性转换为Objective-C中的日期

Dan*_*ins 2 .net c# date objective-c ios

我有一个时间戳,表示自0001年1月1日午夜12:00:00以来经过的100纳秒间隔数(根据http://msdn.microsoft.com/zh-cn/library/system。 datetime.ticks.aspx)。该值由用C#编写的服务器生成,但是我需要在iOS上的Objective-C中将其转换为日期。

例如,时间戳记634794644225861250应该给出2012年8月2日的日期。

Nic*_*rey 5

此C#代码可能会帮助您:

// The Unix epoch is 1970-01-01 00:00:00.000
DateTime   UNIX_EPOCH = new DateTime( 1970 , 1 , 1 ) ;

// The Unix epoch represented in CLR ticks.
// This is also available as UNIX_EPOCH.Ticks
const long UNIX_EPOCH_IN_CLR_TICKS = 621355968000000000 ;

// A CLR tick is 1/10000000 second (100ns).
// Available as Timespan.TicksPerSecond
const long CLR_TICKS_PER_SECOND = 10000000 ;

DateTime now       = DateTime.Now                        ; // current moment in time
long     ticks_now = now.Ticks                           ; // get its number of tics
long     ticks     = ticks_now - UNIX_EPOCH_IN_CLR_TICKS ; // compute the current moment in time as the number of ticks since the Unix epoch began.
long     time_t    = ticks / CLR_TICKS_PER_SECOND        ; // convert that to a time_t, the number of seconds since the Unix Epoch
DateTime computed  = EPOCH.AddSeconds( time_t )          ; // and convert back to a date time value

// 'computed' is the the current time with 1-second precision.
Run Code Online (Sandbox Code Playgroud)

一旦有了time_t值(自Unix纪元开始以来的秒数),您就应该能够因此在Objective-C中获得NSDATE:

NSDate* myNSDate = [NSDate dateWithTimeIntervalSince1970:<my_time_t_value_here> ] ;
Run Code Online (Sandbox Code Playgroud)

请参阅:https : //developer.apple.com/library/ios/#documentation/Cocoa/Reference/Foundation/Classes/NSDate_Class/Reference/Reference.html