How to convert Unix timestamp to DateTime and back in C#?
Hello everyone! I'm a beginner C# developer, and I have a problem with converting Unix timestamp to DateTime and back. \n\nIn my project, I receive time from an API in Unix timestamp format (e.g., 1678901234). I need to display this time in a human-readable format on the UI, and also sometimes send the converted value back to the server. \n\nI tried to write a simple conversion, but something went wrong. Here's my code:\n\n```csharp\n// Trying to convert timestamp to DateTime\nlong timestamp = 1678901234;\nDateTime dateTime = new DateTime(timestamp);\nConsole.WriteLine(dateTime); // Outputs something strange...\n\n// Trying to do the reverse conversion\nDateTime now = DateTime.Now;\nlong backToTimestamp = (long)now.Ticks;\nConsole.WriteLine(backToTimestamp);\n```\n\nProblem
No answers yet.
Log in to leave an answer