tags:

views:

63

answers:

4

Is there a function in c# which returns date&time when given GMT values(-12 to -1 and 1 to 12)?

EDIT:

I have a Dropdownlistbox which contains all GMT values.. Now i want to display date&time of a selected GMT value....

A: 

You can use something like:

var d = System.DateTime.Now().ToUniversalTime().AddHours(5)
Paulo Santos
that won't work, because it delivers a DateTime that has DateTimeKind.Utc.
Cheeso
+2  A: 

GMT is Greenwich Mean Time, right? Or better known as UTC?

I think you're referring to UTC offset.

In other words, given an offset from GMT, what is the time in that spot?

I think it is

DateTime.SpecifyKind(DateTime.UtcNow + new Timespan(offsetHours,0,0),
                     DateTimeKind.LocalTime);

except, that's not really true, because the "kind" of that DateTime will be Local, meaning wherever the computer is right now. What you really want is a DateTimeKind with a particular timezone.

Addendum

Also see the TzTimeZone class that is included in the PublicDomain project on Codeplex: http://www.codeplex.com/publicdomain.

The System.TimeZone as included in .NET 2.0 does not permit an application to instantiate a TimeZone object given a shorthand name of the timezone, or a UTC offset. Instead, the System.TimeZone class "knows" about the local timezone but doesn't do much else. This makes it difficult to take an arbitrary time (say, 3:13pm, October 4th 2006, in Los Angeles) and format it for display in an arbitrary other timezone (say, Paris).

The TzTimeZone class provides a model for a number of different timezones, including their offsets from UTC and the rules they apply for daylight savings time.

With this new set of classes, it is possible to instantiate a timezone from a well-known set of named instances. It is also easy to format a time value w.r.t. any arbitrary (named) timezone. In particular, it is easy to take a time like (3:13pm October 4th 2006, in Los Angeles) and format it for display in Paris.

Cheeso
A: 

Is DateTimeOffset what you are looking for? One of its constructors takes a DateTime and an offset.

shf301
A: 

Paulo's answer should work fine, but the DateTimeOffset struct in .NET 3.5 seems built for your question.

Si