Click here to Skip to main content
15,850,359 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I have tried to get UTC format datetime in c# and tried with below code but not able to get proper value.

string ddd = "2018-02-28T18:10:13+08:00";
DateTime dt = new DateTime();
dt = Convert.ToDateTime(ddd);
//var datetime = new DateTime(dt, DateTimeKind.Local);
var text = dt.ToString("o");
Console.WriteLine(text);
//2018-02-28T15:40:13.0000000+05:30

Getting this value : //2018-02-28T15:40:13.0000000+05:30
need to remove 0000000 from date.

What I have tried:

string ddd = "2018-02-28T18:10:13+08:00";
DateTime dt = new DateTime();
dt = Convert.ToDateTime(ddd);
//var datetime = new DateTime(dt, DateTimeKind.Local);
var text = dt.ToString("o");
Console.WriteLine(text);
//2018-02-28T15:40:13.0000000+05:30
Console.ReadKey();
Posted
Updated 20-Mar-18 2:07am
Comments
Richard Deeming 20-Mar-18 10:26am    
When you're dealing with values that have a UTC offset, you should use DateTimeOffset[^] instead of DateTime.

Or, if you want proper control, use NodaTime[^].

You can't "remove the 0000000 from the date" - DateTime values don't work like that, they are stored as a number of ticks since a particular moment in time, so you can't dump the ticks!

But you can format the output:
C#
string text = dt.ToString("s");
Will give you the UTC format:
2018-02-18T12:10:13
UTC does not have a timezone, so it wouldn't be "+05:30"
But this will add it:
C#
string text = dt.ToString("yyyy-MM-ddTHH:mm:ssK");
 
Share this answer
 
DateTime.UtcNow.ToUniversalTime();
 
Share this answer
 
Comments
Member 12058183 20-Mar-18 7:11am    
Thank you

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900