Reputation: 11851
I have this date here:
DateTime RelevantDate = new DateTime(2017, 11, 13, 16, 0, 0, 0);
request.RelevantDate = Convert.ToDateTime(RelevantDate.ToString("o"));
and I am expecting:
2017-11-13T16:00:00-05:00
Instead I am getting:
2017-11-13T16:00:00
This really needs to be in this format: 2017-11-13T16:00:00-05:00, how can I do that? request.RelevantDate is expecting DateTime
If I do this:
request.RelevantDate = Convert.ToDateTime(DateTime.Now.ToString("o"));
it gives me the correct format:
2017-11-08T06:43:39-05:00
Upvotes: 1
Views: 92
Reputation: 2237
You need to specify timezone if you want to see timezone information in DateTime formatted string.
You can use this approach. Please have a look on it:
If you want to use Local Time Zone
DateTime RelevantDate = new DateTime(2017, 11, 13, 16, 0, 0, 0);
var DateTimeWithZone = TimeZoneInfo.ConvertTime(RelevantDate, TimeZoneInfo.Local);
If you want to use custom timezone
DateTime RelevantDate = new DateTime(2017, 11, 13, 16, 0, 0, 0);
TimeZoneInfo timeZone = TimeZoneInfo.FindSystemTimeZoneById("Central Europe Standard Time");
var DateTimeWithZone = TimeZoneInfo.ConvertTime(RelevantDate, timeZone);
Upvotes: 0
Reputation: 10958
If you create a DateTime
using this constructor its Kind
property is Unspecified
, i.e. it is neither local nor UTC.
DateTime.Now
returns an object with DateTimeKind.Local
, which is why the time zone is added to the output of .ToString("o")
.
You could use another constructor where you can explicitely set the kind to Local
, e.g. new DateTime(2017, 11, 13, 16, 0, 0, 0, DateTimeKind.Local)
.
This way the time zone will be appear in the output of .ToString("o")
.
Upvotes: 6