Convert Date and Time to UTC

It is a common practice amongst developers to store DateTime as Coordinated Universal Time (UTC) in databases, to remove any ambiguity. This way, a user anywhere in the world can retrieve this value from the database and convert it into local datetime.

The TimeZoneInfo class in .NET contains two very useful methods called ConvertTimeToUTC() that converts the current date and time to UTC and ConvertTimeFromUTC() that converts a UTC to the time in a specified time zone.

Here’s how to use it:

static void Main(string[] args)
{
// 24th September, 2010 10:55:23
DateTime dt = new DateTime(2010, 9, 24, 10, 55, 23);

// Convert into UTC
dt = TimeZoneInfo.ConvertTimeToUtc(dt);
Console.WriteLine("UTC Time " + dt);

// Convert UTC to GMT (Greenwich Mean Time)
TimeZoneInfo gmt = TimeZoneInfo.FindSystemTimeZoneById("GMT Standard Time");
dt = TimeZoneInfo.ConvertTimeFromUtc(dt, gmt);
Console.WriteLine("GMT Time " + dt);

Console.ReadLine();
}




OUTPUT

image

Also check my article Convert DateTime to Different TimeZones



Will you give this article a +1 ? Thanks in advance


About The Author

Suprotim Agarwal
Suprotim Agarwal, ASP.NET Architecture MVP (Microsoft Most Valuable Professional) works as an Architect Consultant and provides consultancy on how to design and develop Web applications.

Suprotim is also the founder and primary contributor to DevCurry, DotNetCurry and SQLServerCurry. He is the Editor of a Developer Magazine called DNC Magazine. He has also written two EBooks 51 Recipes using jQuery with ASP.NET Controls. and The Absolutely Awesome jQuery CookBook

Follow him on twitter @suprotimagarwal

1 comment:

Anonymous said...

wow never knew about this api. I plan to use it in my aspnet app now