In case you missed it there is a great blog post on .NET 4.6 which is a part of Windows 10. Among the various performance and Hi-DPI improvements there are some more subtle enhancements. Perhaps as a nod to Microsoft’s new openness to other platforms there are some helper methods on DateTimeOffset for converting to and from UNIX times. These are represented as the number of seconds since 00:00 on the 1st of January 1970. I’d already come across situations where I needed this and had written a couple of simple conversion methods. They come in useful when doing interop with Android APIs for example. Why not match the .NET 4.6 API I thought so slightly tweaked them and put them in a Gist here:-
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
namespace InTheHand | |
{ | |
/// <summary> | |
/// Helper class for DateTimeOffset. | |
/// </summary> | |
public static class DateTimeOffsetHelper | |
{ | |
private static DateTimeOffset dt = new DateTimeOffset(1970, 1, 1, 0, 0, 0, TimeSpan.Zero); | |
/// <summary> | |
/// Converts a Unix time expressed as the number of seconds that have elapsed since 1970-01-01T00:00:00Z to a DateTimeOffset value. | |
/// </summary> | |
/// <param name="seconds">A Unix time, expressed as the number of seconds that have elapsed since 1970-01-01T00:00:00Z (January 1, 1970, at 12:00 AM UTC). | |
/// For Unix times before this date, its value is negative.</param> | |
/// <returns>A date and time value that represents the same moment in time as the Unix time. </returns> | |
public static DateTimeOffset FromUnixTimeSeconds(long seconds) | |
{ | |
return dt.AddSeconds(seconds); | |
} | |
/// <summary> | |
/// Returns the number of seconds that have elapsed since 1970-01-01T00:00:00Z. | |
/// </summary> | |
/// <param name="date">The DateTimeOffset value.</param> | |
/// <returns>The number of seconds that have elapsed since 1970-01-01T00:00:00Z. </returns> | |
/// <remarks>Unix time represents the number of seconds that have elapsed since 1970-01-01T00:00:00Z (January 1, 1970, at 12:00 AM UTC). | |
/// It does not take leap seconds into account. | |
/// <para>This method first converts the current instance to UTC before returning its Unix time. | |
/// For date and time values before 1970-01-01T00:00:00Z, this method returns a negative value.</para></remarks> | |
public static long ToUnixTimeSeconds(this DateTimeOffset date) | |
{ | |
return Convert.ToInt64(date.Subtract(dt).TotalSeconds); | |
} | |
} | |
} |
One reply on “.NET 4.6 and DateTime extras”
[…] .NET 4.6 and DateTime extras – Peter Freeman Foot […]