i need to convert a NSDate to C# ticks.
DateTime.ticks converts date to ticks starting from January 1 0001.
How can i do that? Thanks in advance.
i need to convert a NSDate to C# ticks.
DateTime.ticks converts date to ticks starting from January 1 0001.
How can i do that? Thanks in advance.
The OP tagged his question with Swift, so here's an alternative answer, although it is basically the same as Nikolay has posted. However, this version adds support for mapping DateTime.MinValue and DateTime.MaxValue to/from Date.distantPast and 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
}
I borrowed this code somewhere, so I'm not an author. Here it goes:
@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