Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get UTC equivalent for my local time in C#

Tags:

c#

datetime

My machine is on PDT and if I say DateTime.Now, then I will get a local time which is say equivalent to Sep-18th 2012 6:00:00 AM. I want to get UTC equivalent for this datetime instance. UTC time will be 7 hours ahead Of PDT and 8 hours ahead of PST. I want to consider daylight saving automatically.

Any idea on how I can do this?

like image 316
Amit Avatar asked Sep 18 '12 18:09

Amit


People also ask

What is the UTC time in C?

The gmtime() function in C++ change the time, which is given to UTC(Universal Time Coordinated) time (i.e., the time at the GMT timezone). The gmtime() is defined in ctime header file. Parameters: The function accepts one mandatory parameter current_time : which specifies a pointer to a time_t object.

How do you convert time to UTC?

Add the local time offset to the UTC time. For example, if your local time offset is -5:00, and if the UTC time is shown as 11:00, add -5 to 11. The time setting when adjusted for offset is 06:00 (6:00 A.M.). Note The date also follows UTC format.

How do I get UTC time in C #?

The gmtime() function is a library function which is defined in <time. h> header file, it is used to get the current Coordinated Universal Time (UTC) time. Syntax: tm* gmtime ( const time_t* current_time );

What is UTC in CT?

Central Standard Time is UTC-6, while Central Daylight Time is UTC-5.


1 Answers

You can use

var now = DateTime.UtcNow;

To convert an existing DateTime, assuming it has time zone information, you can use DateTime.ToUniversalTime(). If you get the DateTime instance using e.g.

var localNow = DateTime.Now;  // Has timezone info

it will have time zone information. If you create it e.g. using a tick count, it will not contain timezone information unless you explicitly supply it.

var unspecifiedNow = new DateTime(someTickCount); // No timezone info

It is worth mentioning that timezone handling in .NET is not optimal.  You may wish to have a look at Noda Time (a project by Jon Skeet) if you need to do anything elaborate involving time zones.

like image 158
Eric J. Avatar answered Oct 07 '22 19:10

Eric J.