2013-08-01 104 views
8

我曾經遇到過以下的C#代碼功能:如何獲得UNIX時間戳淨

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; 
} 

...,只是不知道是否有達到同樣的效果有些最短,最徹底的方法?

謝謝

+0

這大概[問題] [1]可以幫助你。 [1]:http://stackoverflow.com/questions/249760/how-to-convert-unix-timestamp-to-datetime-and-vice-versa –

回答

9

您可以使用以下方法:

long CurrentTimestamp = (DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, 0)).TotalSeconds; 

雖然這已經回答了在SO多次

+0

我想'DateTime.UtcNow'是正確的選擇。 – Joey

+1

'TotalSeconds'不會返回一個double值嗎? –

+6

這已經被多次解答,並且你還是錯了:)你必須在某些時區使用DateTime(1970,1,1,0,0,0,0,System.DateTimeKind.Utc)或夏令時導致錯誤的結果 – rouen