Skip to content

Instantly share code, notes, and snippets.

@sadrakgunadi
Last active February 5, 2019 01:42
Show Gist options
  • Save sadrakgunadi/d7a5b7fd546534b84e1da10b7d48d2ab to your computer and use it in GitHub Desktop.
Save sadrakgunadi/d7a5b7fd546534b84e1da10b7d48d2ab to your computer and use it in GitHub Desktop.
Convert Date Time to Unix Time Stamp and Vice Versa

SG.UnixTime

Unix Time Converter

Convert Date Time to Unix Timestamp and Vice Versa (seconds or milliseconds format)

Import Reference

using SG.UnixTime;

Convert DateTime to Unix Timestamp

example 1 :

DateTime currentDateTime = DateTime.Now;
Int32 epoch = 0;

epoch = UnixTime.ToEpoch(currentDateTime);
Console.WriteLine(epoch);

example 2 (to seconds with inferred type) :

DateTime currentDateTime = DateTime.Now;
Int32 epoch = 0;

epoch = UnixTime.ToEpoch<Int32>(currentDateTime, ConvertFormat.ToSeconds);
Console.WriteLine(epoch);

example 3 (to milliseconds with inferred type) :

DateTime currentDateTime = DateTime.Now;
long epoch = 0;

epoch = UnixTime.ToEpoch<long>(currentDateTime, ConvertFormat.ToMilliseconds);
Console.WriteLine(epoch);

Convert Unix Timestamp to DateTime

example 1 :

DateTime defaultTime = DateTime.Now;

defaultTime = UnixTime.ToDateTime(epoch);
Console.WriteLine(defaultTime);

example 2 :

 DateTime defaultTime = DateTime.Now;

defaultTime = UnixTime.ToDateTime<Int32>(epoch, ConvertFormat.ToSeconds);
Console.WriteLine(defaultTime);

example 3 :

DateTime defaultTime = DateTime.Now;

defaultTime = UnixTime.ToDateTime <long>(epoch, ConvertFormat.ToMilliseconds);
Console.WriteLine(defaultTime);

Add seconds from current Unix Timestamp

Int32 epoch = 0;
epoch = UnixTime.ToEpoch<Int32>(currentDateTime, ConvertFormat.ToSeconds);

int seconds = 10;
Int32 addSeconds = UnixTime.AddSeconds(epoch, seconds);

Add milliseconds from current Unix Timestamp

Int32 epoch = 0;
epoch = UnixTime.ToEpoch<Int32>(currentDateTime, ConvertFormat.ToSeconds);

int milliseconds = 2000;
Int32 addmilliseconds = UnixTime.AddMilliseconds(epoch, milliseconds);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment