Click here to Skip to main content
15,891,529 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I got function which is converting UNIX time to DaTime which is working great anyhow now i need function to convert from DateTime to UNIX timestamp but something is wrong with this because when i am passing DateTime somehow the last 3 digits are not shown for instance i have this timestamp:

C#
1300124700345


which is equal to:

C#
14.03.2011 5:45 PM


When i pass that to below function i am retreiving:

C#
1300124700


3 last digits dissaperd somehow always. Could you help here?

C#
static readonly DateTime UnixEpoch =
       new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc);

public static long ToUnixTime(DateTime date)
{
    return Convert.ToInt64((date - UnixEpoch).TotalSeconds);
}
Posted

 
Share this answer
 
Comments
carlito_brigante 1-Sep-14 5:51am    
already tried same result - the 3 last digits was cutted of.
You are only using seconds. Try to add it as millisecornds like this:
C#
public static DateTime? ConvertUnixTimeStamp(string unixTimeStamp)
{
    return new DateTime(1970, 1, 1, 0, 0, 0).AddMilliseconds(Convert.ToDouble(unixTimeStamp));
}


Good luck!
 
Share this answer
 
v2
Comments
carlito_brigante 1-Sep-14 5:51am    
your version is from unix time to datetime but i need from datetime to unix...
E.F. Nijboer 1-Sep-14 9:33am    
Ah yes, sorry. Try change your code in ToUnixTime to this:

return Convert.ToInt64((date - UnixEpoch).TotalMilliseconds);

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900