Kgn-web
Kgn-web

Reputation: 7555

How to convert C# datetime value to UTC timezone

I am in need to pass value of type DateTime to an API in the below format

2018-12-02T07:00:00.000Z //required format

but the datetime value from Db I am getting is as

2018-10-25 05:30:00.0000000

Now using the .ToString("o"), the value formatted as

2018-10-25T05:30:00.0000000

Checked below SO links

Where's the DateTime 'Z' format specifier?

http://stackoverflow.com/questions/9163977/converting-datetime-to-z-format

but not converting into the required format.

My understanding is having Z in the datetime represents UtcTimeZone.

Upvotes: 2

Views: 1083

Answers (1)

Vivien Sonntag
Vivien Sonntag

Reputation: 4629

Are you looking for something like this?

var baseTime = DateTime.Parse("2018-10-25 05:30:00.0000000");
var utcTime = baseTime.ToUniversalTime();
Console.WriteLine(utcTime.ToString("yyyy-MM-ddTHH:mm:ss.fffZ"));

You can try it out here: https://dotnetfiddle.net/HsdMcu

If you have summer and winter time in your region you might need to use a bit more sophisticated way for parsing your intial time correctly, this can be found in this answer.

Upvotes: 3

Related Questions