Converting DateTime to Unix TimeStap in Local Time

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 :

  1. /// <summary>   
  2. /// Convers to unix date time stamp way1.   
  3. /// </summary>   
  4. /// <param name="dateToConvert">The date to convert.</param>   
  5. /// <returns></returns>   
  6. public static long ConverToUnixDateTimeStampWay1(DateTime dateToConvert)  
  7. {  
  8.     TimeSpan timeSpan = (dateToConvert.ToUniversalTime() - new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Local));  
  9.     return Convert.ToInt64(timeSpan.TotalSeconds);  
  10. }  
Way2 :
  1. /// <summary>   
  2. /// Convers to unix date time stamp way2.   
  3. /// </summary>   
  4. /// <param name="dateToConvert">The date to convert.</param>   
  5. /// <param name="dateFormat">The date format.</param>   
  6. /// <returns></returns>   
  7. public static string ConverToUnixDateTimeStampWay2(string dateToConvert, string dateFormat)  
  8. {  
  9.     DateTime dtToConvert = new DateTime();  
  10.     DateTime.TryParseExact(dateToConvert, dateFormat, null, DateTimeStyles.AssumeLocal, out dtToConvert);  
  11.   
  12.     //in the below statement DateTime.Parse("01 /01/1970 00:00:00") is not safe and will throw exception while changing DateTimeFormat   
  13.     long ticks = dtToConvert.Subtract(new TimeSpan(1, 0, 0)).Ticks - DateTime.Parse("01/01/1970 00:00:00").Ticks;  
  14.     ticks /= 10000000; //Convert windows ticks to seconds   
  15.     return ticks.ToString();  
  16. }  
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.