Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get Unix time stamp in .NET? [duplicate]

Tags:

c#

.net

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?

like image 776
user576700 Avatar asked Aug 01 '13 13:08

user576700


1 Answers

you can use the following:

long CurrentTimestamp = (DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, 0)).TotalSeconds;
like image 176
bizzehdee Avatar answered Oct 08 '22 22:10

bizzehdee