Lee Whitney III
Lee Whitney III

Reputation: 10978

How can a .NET date be converted to NSTimeInterval?

We have .NET code (C#) that writes to a SQLite database, which is then read by an iOS (iPhone) app with objective-c.

The date format used in SQLite is NSTimeInterval (to NSDate with dateWithIntervalSince1970) because it's efficient on the iPhone.

How can .NET DateTime be converted to NSTimeInterval so that when it is extracted with dateWithIntervalSince1970 the date is correct?

Notes: 1) I tried to search on how NSTimeInterval works fundamentally but only find this opaque documentation: http://developer.apple.com/library/mac/#documentation/Cocoa/Reference/Foundation/Miscellaneous/Foundation_DataTypes/Reference/reference.html

2) Although C# code would be ideal I'd be happy with pseudo-code that goes from 3 ints (year/month/day) to a double.

Upvotes: 2

Views: 1238

Answers (2)

Jonathan Grynspan
Jonathan Grynspan

Reputation: 43472

I think you mean NSTimeInterval. NSTimeInterval represents a span of time, in seconds, so its logical equivalent in .NET is System.TimeSpan rather than System.DateTime. But, if you specify it as the span of time since January 1, 1970 00:00:00 GMT, which is what you get with -timeIntervalSince1970, then the conversion between it and System.DateTime becomes possible.

To convert between System.DateTime and a POSIX timestamp (which is what NSTimeInterval is in this situation, plus subsecond precision), you probably want something like this:

DateTime unixEpoch = new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc);
DateTime dt = ...;
double intervalSince1970 = (dt - unixEpoch).TotalSeconds;

To go the other way:

DateTime unixEpoch = new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc);
double intervalSince1970 = ...;
DateTime dt = unixEpoch + TimeSpan.FromSeconds(intervalSince1970);

Upvotes: 4

Michael D. Irizarry
Michael D. Irizarry

Reputation: 6302

This is what we have in one of our utils hope it helps.

private static double GetUnixEpoch(this DateTime dateTime)
{
    var unixTime = dateTime.ToUniversalTime() - 
        new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);

    return unixTime.TotalSeconds;
}

var epochTime = DateTime.Now.GetUnixEpoch();

And if you want to get future date it also works

30 Minutes into the future

var unixTime2 = (DateTime.Now + new TimeSpan(0, 30, 0)).GetUnixEpoch();

Upvotes: 0

Related Questions