Transformation Thursday - How do I Check Whether it is DST in Ruby and CSharp?

September 11, 2014

Today I was playing around with some date and times, I was wondering how could I determine whether daylight savings (DST) was in effect?

So since I am learning Ruby I first tried to do the solution in C# and then Ruby. Here is the C# code.

Currently, I am in San Jose, California where DST is in effect. In the code above you can see that the there is a static property called ‘Local’ on the ‘TimeZoneInfo’ class that gives us access to an instance of the current time zone as set by Windows. The ‘TimeZoneInfo’ class has a method creatively called ‘IsDaylightSavingTime’ which takes a ‘DateTime’ object and gives an indication whether DST is in effect or not.

To prove that this works I get an instance of the ‘TimeZoneInfo’ class with its time zone set to South Africa Standard Time where I know they don’t have DST.

I output the results of calling ‘IsDaylightSavingTime’ on the instance set to West Pacific Standard Time (California) and on the instance set to ‘South Africa Standard Time’. These calls return true and false which are both correct.

Next let’s do the same using Ruby.

We ask the ‘Time’ class an instance of the current time and then call the ‘isdst’ method which returns a bool indicating whether or not it is DST. Again to show this is working I change the time zone to ‘Africa/Johannesburg’ and as expected we get the correct results.

Both languages make it simple to determine whether or not DST is in effect. Ruby however does so in fewer keystrokes and to me at least that makes a difference.

Discussion, links, and tweets

My name is Deon Heyns and I am a developer learning things and documenting them in realtime. Python, Ruby, Scala, .NET, and Groovy are all languages I have written code in. I appeared in the New York Post once. I host my code up at GitHub and Bitbucket so have a look at my code, fork it and send those pull requests.

comments powered by Disqus