The unix time stamp is the number of seconds between a particular date and the Unix Epoch. The counts of Unix Epoch start on 01-Jan-1970 at UTC.
But sometimes we need to calculate the time stamp as per local time. Suppose an event has been occurred on 01-Jan-1990 00:00 IST (GMT + 5:30) and I convert it to time stamp as per UTC then here will be difference of 5:30 hrs. To get exact time stamp with 00:00 hrs difference I am converting it as per local time.
Way1 :
/// <summary>
/// Convers to unix date time stamp way1.
/// </summary>
/// <param name="dateToConvert">The date to convert.</param>
/// <returns></returns>
public static long ConverToUnixDateTimeStampWay1(DateTime dateToConvert)
{
TimeSpan timeSpan = (dateToConvert.ToUniversalTime() - new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Local));
return Convert.ToInt64(timeSpan.TotalSeconds);
} Way2 :/// <summary>
/// Convers to unix date time stamp way2.
/// </summary>
/// <param name="dateToConvert">The date to convert.</param>
/// <param name="dateFormat">The date format.</param>
/// <returns></returns>
public static string ConverToUnixDateTimeStampWay2(string dateToConvert, string dateFormat)
{
DateTime dtToConvert = new DateTime();
DateTime.TryParseExact(dateToConvert, dateFormat, null, DateTimeStyles.AssumeLocal, out dtToConvert);
//in the below statement DateTime.Parse("01 /01/1970 00:00:00") is not safe and will throw exception while changing DateTimeFormat
long ticks = dtToConvert.Subtract(new TimeSpan(1, 0, 0)).Ticks - DateTime.Parse("01/01/1970 00:00:00").Ticks;
ticks /= 10000000; //Convert windows ticks to seconds
return ticks.ToString();
} In both of the above methods you can see that I am storing all data in long (System.Int64) instead of int (System.Int32).If I store time stamp in int (System.Int32) then it will throw exception for any date after 19-January-2038.
