将.NET DateTime.Ticks属性转换为Objective-C中的日期 [英] Convert .NET DateTime.Ticks Property to Date in Objective-C

查看:91
本文介绍了将.NET DateTime.Ticks属性转换为Objective-C中的日期的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a timestamp that represents the the number of 100-nanosecond intervals that have elapsed since 12:00:00 midnight, January 1, 0001 (according to http://msdn.microsoft.com/en-us/library/system.datetime.ticks.aspx). This value is generated by a server written in C#, but I need to convert this to a date in Objective-C on iOS.

例如,假定时间戳为634794644225861250给出日期为2012年8月2日。

For example, the timestamp 634794644225861250 is supposed to give a date of August 2, 2012.

推荐答案

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

This C# code might help you:

// 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.

一旦您拥有 time_t 的值,从Unix时代开始算起的秒数,您应该就能在Objective-C中获得NSDATE:

Once you have your time_t value, the number of seconds since the Unix epoch began, you should be able to get an NSDATE in Objective-C thusly:

NSDate* myNSDate = [NSDate dateWithTimeIntervalSince1970:<my_time_t_value_here> ] ;

其中: https://developer.apple.com/library/ios/#documentation/Cocoa/Reference/Foundation/Classes /NSDate_Class/Reference/Reference.html

这篇关于将.NET DateTime.Ticks属性转换为Objective-C中的日期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆