2013-08-01 17 views
8

ho incontrato seguente funzione nel codice C#:Come ottenere unix timestamp in Net

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

... e chiedo solo se c'è qualche via più breve e più pulito per ottenere lo stesso effetto?

Grazie

+0

Probabilmente questo [domanda] [1] potrebbero aiutarvi. [1]: http://stackoverflow.com/questions/249760/how-to-convert-unix-timestamp-to-datetime-and-vice-versa –

risposta

9

è possibile utilizzare il seguente:

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

anche se questo è stato risposto il SO più volte

+0

Credo 'DateTime.UtcNow' è la scelta giusta – Joey

+1

Non 'TotalSeconds' restituisce un doppio valore? –

+6

questo è stato risposto più volte su SO, e ancora ti sei sbagliato :) devi usare DateTime (1970, 1, 1, 0, 0, 0, 0, System.DateTimeKind.Utc) o l'ora legale in alcuni fusi orari causare risultati errati – rouen