user999822
user999822

Reputation: 445

ASP.Net C# UTC/GMT DateTime

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#.

Upvotes: 0

Views: 4178

Answers (1)

Jon Skeet
Jon Skeet

Reputation: 1500105

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?

Upvotes: 3

Related Questions