11

I have encountered following function in C# code:

Byte[] GetUNIXTimeStamp(DateTime dtVal)
{
  if (m_bytTimeStamp == null) m_bytTimeStamp = new Byte[14];

  Byte[] bytVals = BitConverter.GetBytes((UInt16)dtVal.Day);
  m_bytTimeStamp[0] = bytVals[0];
  m_bytTimeStamp[1] = bytVals[1];
  bytVals = BitConverter.GetBytes((UInt16)dtVal.Month);
  m_bytTimeStamp[2] = bytVals[0];
  m_bytTimeStamp[3] = bytVals[1];
  bytVals = BitConverter.GetBytes((UInt16)dtVal.Year);
  m_bytTimeStamp[4] = bytVals[0];
  m_bytTimeStamp[5] = bytVals[1];
  bytVals = BitConverter.GetBytes((UInt16)dtVal.Hour);
  m_bytTimeStamp[6] = bytVals[0];
  m_bytTimeStamp[7] = bytVals[1];
  bytVals = BitConverter.GetBytes((UInt16)dtVal.Minute);
  m_bytTimeStamp[8] = bytVals[0];
  m_bytTimeStamp[9] = bytVals[1];
  bytVals = BitConverter.GetBytes((UInt16)dtVal.Second);
  m_bytTimeStamp[10] = bytVals[0];
  m_bytTimeStamp[11] = bytVals[1];
  bytVals = BitConverter.GetBytes((UInt16)dtVal.Millisecond);
  m_bytTimeStamp[12] = bytVals[0];
  m_bytTimeStamp[13] = bytVals[1];

  return m_bytTimeStamp;
}

…and just wondering if there is some shortest and cleanest way to achieve the same effect?

Uwe Keim
  • 39,551
  • 56
  • 175
  • 291
user576700
  • 591
  • 1
  • 6
  • 15
  • Probably this [question][1] might help you. [1]: http://stackoverflow.com/questions/249760/how-to-convert-unix-timestamp-to-datetime-and-vice-versa – Tamim Al Manaseer Aug 01 '13 at 13:12

1 Answers1

15

you can use the following:

long CurrentTimestamp = (DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, 0)).TotalSeconds;
Brian Webster
  • 30,033
  • 48
  • 152
  • 225
bizzehdee
  • 20,289
  • 11
  • 46
  • 76
  • 1
    I guess `DateTime.UtcNow` is the correct choice. – Joey Aug 01 '13 at 13:23
  • 1
    Doesn't `TotalSeconds` return a double value? – ingh.am Feb 14 '14 at 12:08
  • 7
    this has been answered on SO multiple times, and still you got it wrong :) you must use DateTime(1970, 1, 1, 0, 0, 0, 0, System.DateTimeKind.Utc) or daylight saving in some timezones will cause wrong results – rouen Jun 25 '14 at 11:58
  • Not beautiful but the idea is here: `string timestamp = ("" + (DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc)).TotalSeconds) .Split('.').First();` – Bgi Aug 27 '14 at 15:26
  • 21
    For getting that I now use `DateTimeOffset.UtcNow.ToUnixTimeSeconds()` – Jason Goemaat Mar 16 '17 at 21:23
  • 1
    @JasonGoemaat Only available on .NET 4.6 and up. – Vahid Amiri May 13 '19 at 11:51