0

I want get UTC 0 time which was Greenwich Mean Time (GMT).

I try to DateTime.UtcNow and DateTime.Now.ToUniversalTime() but its returns wrong times. İts return 22:40 instead of 06:40

How can I get UTC/GMT time in C#.

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
user999822
  • 445
  • 1
  • 9
  • 17
  • Removed the asp.net tag - if you want to include it again, make sure the question shows why you believe it's relevant. – Jon Skeet Oct 17 '12 at 06:50

1 Answers1

3

I try to DateTime.UtcNow and DateTime.Now.ToUniversalTime() but its returns wrong times.

No, it really doesn't. (I would strongly advise using the former rather than the latter though. In general, converting from a local time to UTC can be ambiguous due to daylight saving transitions. I believe in this particular case it may do the right thing, but UtcNow is a better approach.)

DateTime.UtcNow does return the current UTC time. If it's giving you the wrong result, then your system clock is wrong - or you're performing some other transformation of the value somewhere (e.g. converting it to local time as part of formatting).

Basically, you're using the right property, so you need to diagnose where exactly the result is going wrong.

I suggest you start off with a small console app:

class ShowTimes
{
    static void Main()
    {
        Console.WriteLine("Local time: {0}", DateTime.Now);
        Console.WriteLine("UTC time: {0}", DateTime.UtcNow);
    }
}

What does that show, and what time zone are you in?

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
  • I dont transform datetime anywhere. How can I check system time is wrong or right in VS? – user999822 Oct 17 '12 at 06:59
  • @user999822: You may not *think* you transform it... but it can happen in unexpected ways sometimes. Look at your system clock in Windows, and check what time zone it thinks it's in. I'll edit the question with some sample code too. – Jon Skeet Oct 17 '12 at 07:03
  • Local Time : 10:11:42 UTC Time : 17:11:42 Local Time my computer time right but UTC Time nis wrong. real utc time 07:11:42. I am in GMT+3 time zone. – user999822 Oct 17 '12 at 07:12
  • @user999822: Well clearly your computer doesn't think you're in a GMT+3 time zone... you should look at the date/time settings in the OS. – Jon Skeet Oct 17 '12 at 07:50