简体   繁体   中英

Convert Unix Epoch Timestamp to DateTime and back

I convert the date and time 19/03/2019 14:23:00 into a Unix Epoch TimeStamp and then back into a DateTime object. The conversion succeeded excepting the year, which resulted 0050 in stead of 2019. I do not know what I did wrong in the conversion process, back to DateTime. The code is the following:

DateTime targetDateTime = new DateTime(2019, 03, 19, 14, 23, 00, DateTimeKind.Local);
DateTime epoch = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);    
long unixDateTime = (long)(targetDateTime.ToUniversalTime() - epoch).TotalSeconds;
TimeSpan resultingTimeSpan = TimeSpan.FromSeconds(unixDateTime);
DateTime localDateTime = new 
DateTime(resultingTimeSpan.Ticks).ToLocalTime();

The localDateTime.Year resulted: 0050 Please help.

If your purpose is to get the ticks from a datetime value and then convert it back to the original datetime value, you can use the following code

DateTime targetDateTime = new DateTime(2019, 03, 19, 14, 23, 00, DateTimeKind.Local);

var totalTicks = targetDateTime.ToUniversalTime().Ticks;

DateTime localDateTime = new DateTime(totalTicks, DateTimeKind.Utc).ToLocalTime();

If you still want to get the ticks value regarding the epoch time, then this code can help

DateTime targetDateTime = new DateTime(2019, 03, 19, 14, 23, 00, DateTimeKind.Local);
DateTime epoch = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);
long unixDateTime = (targetDateTime.ToUniversalTime() - epoch).Ticks;

 //Add the ticks back to the epoch
 var utcTime = epoch.AddTicks(unixDateTime);
 DateTime localDateTime = utcTime.ToLocalTime();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM