I have checked this question DateTime local and utc the same, but still have no idea.
Here's my code
DateTime localNow = DateTime.Now;
DateTime utcNow = DateTime.UtcNow;
Int64 localTimeStamp = ((DateTimeOffset)localNow).ToUnixTimeSeconds();
Int64 utcTimeStamp = ((DateTimeOffset)utcNow).ToUnixTimeSeconds();
Console.WriteLine("With Datetime");
Console.WriteLine("Current time: " + localNow.ToString("yyyy/MM/dd HH:mm:ss") + " timestamp: " + localTimeStamp);
Console.WriteLine("Current Utc time: " + utcNow.ToString("yyyy/MM/dd HH:mm:ss") + " timestamp: " + utcTimeStamp);
DateTimeOffset localNowOff = DateTimeOffset.Now;
DateTimeOffset utcNowOff = DateTimeOffset.UtcNow;
Int64 localOffTimeStamp = localNowOff.ToUnixTimeSeconds();
Int64 utcOffTimeStamp = utcNowOff.ToUnixTimeSeconds();
Console.WriteLine("With DatetimeOffset");
Console.WriteLine("Current time: " + localNowOff.ToString("yyyy/MM/dd HH:mm:ss") + " timestamp: " + localOffTimeStamp);
Console.WriteLine("Current Utc time: " + utcNowOff.ToString("yyyy/MM/dd HH:mm:ss") + " timestamp: " + utcOffTimeStamp);
And heres' the output:
With Datetime
Current time: 2023/10/31 23:11:33 timestamp: 1698765093
Current Utc time: 2023/10/31 15:11:33 timestamp: 1698765093
With DatetimeOffset
Current time: 2023/10/31 23:11:33 timestamp: 1698765093
Current Utc time: 2023/10/31 15:11:33 timestamp: 1698765093
I don't believe the timestamp result between local ant utc should be the same, but it did happen.
However, when i try get local datetime from the timestamp, it turns out to be utc datetime, like this:
DateTime localNow = DateTime.Now;
Int64 localTimeStamp = ((DateTimeOffset)localNow).ToUnixTimeSeconds();
DateTime localDateTime = new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Local);
localDateTime = localDateTime.AddSeconds(localTimeStamp).ToLocalTime();
Console.WriteLine("Convert local timestamp to datetime: " + localDateTime.ToString("yyyy/MM/dd HH:mm:ss"));
So am i doing anything wrong and what's the proper way to get the timestamp about local time and utc time and convert back to datetime?
There is no local unix timestamp as the epoch unix timestamp is always UTC+0.
If you want to convert the timestamp to local do something like this:
DateTimeOffset dt = DateTimeOffset.FromUnixTimeSeconds(1698766249);
DateTime localDt = dt.LocalDateTime;