In The C# Language, What Is The Method For Converting A Unix Timestamp To DateTime And Vice Versa?

To convert a Unix timestamp to DateTime in C#, you can use the DateTimeOffset.FromUnixTimeSeconds() method. Here’s an example:

long unixTimestamp = 1631839200; // Replace with your Unix timestamp

DateTimeOffset dateTimeOffset = DateTimeOffset.FromUnixTimeSeconds(unixTimestamp);
DateTime dateTime = dateTimeOffset.UtcDateTime;

Console.WriteLine(dateTime);

To convert DateTime to a Unix timestamp, you can use the DateTimeOffset.ToUnixTimeSeconds() method. Here’s an example:

DateTime dateTime = new DateTime(2021, 9, 17, 0, 0, 0, DateTimeKind.Utc); // Replace with your DateTime

DateTimeOffset dateTimeOffset = new DateTimeOffset(dateTime);
long unixTimestamp = dateTimeOffset.ToUnixTimeSeconds();

Console.WriteLine(unixTimestamp);

Make sure to replace 1631839200 with your Unix timestamp or new DateTime(2021, 9, 17, 0, 0, 0, DateTimeKind.Utc) with your DateTime, as per requirement.

About the Author Rex

I'm a passionate tech blogger with an insatiable love for programming! From my early days tinkering with code, I've delved into web dev, mobile apps, and AI. Sharing insights and tutorials with the world is my joy, connecting me to a global community of like-minded tech enthusiasts. Python holds a special place in my heart, but I embrace all challenges. Constantly learning, I attend tech conferences, contribute to open-source projects, and engage in code review sessions. My ultimate goal is to inspire the next generation of developers and contribute positively to the ever-evolving tech landscape. Let's code together!