Last active
May 30, 2017 02:41
-
-
Save happyjem/2d6fcf2edd5c9d4b1eb8f08e1b5bf1a4 to your computer and use it in GitHub Desktop.
.NET Unix Time to Date Time After .Net 4.6
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 TestForUnxTime | |
{ | |
//reference : https://msdn.microsoft.com/ko-kr/library/system.datetimeoffset.fromunixtimeseconds(v=vs.110).aspx | |
class MainClass | |
{ | |
public static void Main(string[] args) | |
{ | |
//before Net 4.6 | |
//miliSeconds 단위, 만약 unixtime 이 second단위로 온다면, 1000을 곱한다. | |
var date = UnixTimeStampToDateTimeForOld(1495985199000); | |
String fortmatedDateStr = String.Format("{0:yyyy/MM/dd hh:mm:ss}", date); | |
Console.WriteLine(fortmatedDateStr); | |
//After Net 4.6 | |
var dateTime = UnixTimeStampToDateTimeForNew(1495985199); | |
String fortmatedDateStr2 = String.Format("{0:yyyy/MM/dd hh:mm:ss}", dateTime); | |
Console.WriteLine("Test Time to UnixTime : {0}", fortmatedDateStr2); | |
Console.WriteLine(fortmatedDateStr2); | |
var testUnixTime = DateTimeToUnixTimeStamp(); | |
Console.WriteLine("Test Unix Time For 2017.05.30 : {0}", testUnixTime); | |
} | |
//after 4.6 | |
private static DateTime UnixTimeStampToDateTimeForNew(long unixTimeStamp) | |
{ | |
var dateTimeOffset = DateTimeOffset.FromUnixTimeSeconds(unixTimeStamp); | |
var dateTime = dateTimeOffset.DateTime; | |
return dateTime; | |
} | |
//before 4.6 | |
//refernce: https://stackoverflow.com/questions/28305153/how-convert-unix-timestamp-to-datetime | |
private static DateTime UnixTimeStampToDateTimeForOld(long unixTimeStamp) | |
{ | |
var epoch = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Local); | |
return epoch.AddMilliseconds(unixTimeStamp); | |
} | |
//Seconds 단위 | |
private static long DateTimeToUnixTimeStamp() | |
{ | |
//Test | |
var dateTime = new DateTime(2017, 05, 30, 11, 14, 0, DateTimeKind.Local); | |
var dateTimeOffset = new DateTimeOffset(dateTime); | |
var unixDateTime = dateTimeOffset.ToUnixTimeSeconds(); | |
return unixDateTime; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment