Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# DateTime time zone subtract issues

I have this line of code:

double seconds = new DateTime(2006,7,6,12,1,0,DateTimeKind.Local).Subtract(new DateTime(1970,1,1,0,0,0,DateTimeKind.Local).TotalSeconds;

This was not the right number I wanted, so I tried the following:

double seconds = new DateTime(2006,7,6,12,1,0,DateTimeKind.Local).Subtract(new DateTime(1970,1,1,0,0,0,DateTimeKind.Utc).TotalSeconds;

(The difference is that in one case, I use local time for the epoch, and in the other, I use UTC). Interestingly though, they're both giving me the same value, and I don't know why this is. I live at -600 GMT, so DateTimeKind.Local should actually affect things.

Thanks in advance!

like image 656
codersarepeople Avatar asked Jul 29 '10 03:07

codersarepeople


People also ask

What C is used for?

C programming language is a machine-independent programming language that is mainly used to create many types of applications and operating systems such as Windows, and other complicated programs such as the Oracle database, Git, Python interpreter, and games and is considered a programming foundation in the process of ...

Is C language easy?

C is a general-purpose language that most programmers learn before moving on to more complex languages. From Unix and Windows to Tic Tac Toe and Photoshop, several of the most commonly used applications today have been built on C. It is easy to learn because: A simple syntax with only 32 keywords.

What is C in C language?

What is C? C is a general-purpose programming language created by Dennis Ritchie at the Bell Laboratories in 1972. It is a very popular language, despite being old. C is strongly associated with UNIX, as it was developed to write the UNIX operating system.

What is the full name of C?

In the real sense it has no meaning or full form. It was developed by Dennis Ritchie and Ken Thompson at AT&T bell Lab. First, they used to call it as B language then later they made some improvement into it and renamed it as C and its superscript as C++ which was invented by Dr.


1 Answers

In the DateTimeKind page on MSDN (http://msdn.microsoft.com/en-us/library/shx7s921.aspx), it states:

The members of the DateTimeKind enumeration are used in conversion operations between local time and Coordinated Universal Time (UTC), but not in comparison or arithmetic operations. For more information about time conversions, see Converting Times Between Time Zones.

The advice there says to use TimeZoneInfo.ConvertTimeToUtc

So, based on that, the code should probably be modified to:

double seconds = new DateTime(2006,7,6,12,1,0,DateTimeKind.Local).Subtract(TimeZoneInfo.ConvertTimeToUtc(new DateTime(1970,1,1,0,0,0,DateTimeKind.Local)).TotalSeconds
like image 130
mkedobbs Avatar answered Oct 03 '22 22:10

mkedobbs