Skip to content

Instantly share code, notes, and snippets.

@atifaziz
Created October 6, 2016 11:34
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save atifaziz/a9ccee5ff1a2be2455489a3ebdcb3314 to your computer and use it in GitHub Desktop.
Save atifaziz/a9ccee5ff1a2be2455489a3ebdcb3314 to your computer and use it in GitHub Desktop.
C# functions to convert to/from Unix time (seconds since Jan 1, 1970, midnight UTC)
#region Copyright (c) 2016 Atif Aziz. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
#endregion
using System;
// NOTE: .NET Framework 4.6 has built-in functions:
// - DateTimeOffset.FromUnixTimeSeconds
// https://msdn.microsoft.com/en-us/library/system.datetimeoffset.fromunixtimeseconds.aspx
// - DateTimeOffset.ToUnixTimeSeconds
// https://msdn.microsoft.com/en-us/library/system.datetimeoffset.tounixtimeseconds.aspx
public static class UnixTime
{
public static DateTimeOffset Epoch = new DateTimeOffset(new DateTime(1970, 1, 1), TimeSpan.Zero);
public static double From(DateTimeOffset time) =>
(time.ToUniversalTime() - Epoch).TotalSeconds;
public static double From(DateTime time) =>
(time.ToUniversalTime() - Epoch).TotalSeconds;
public static DateTimeOffset ToDateTimeOffset(double seconds) =>
Epoch.AddSeconds(seconds);
public static DateTimeOffset ToDateTime(double seconds) =>
ToDateTimeOffset(seconds).LocalDateTime;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment