1

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

user979331
  • 11,039
  • 73
  • 223
  • 418
  • 1
    have a look at https://stackoverflow.com/questions/39071415/convert-todatetimedatestring-to-required-dd-mm-yyyy-format-of-date, look careful to this option: "M/d/yyyy h:mm:ss tt" – Iria Nov 08 '17 at 11:48

2 Answers2

6

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").

Dirk
  • 10,668
  • 2
  • 35
  • 49
0

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);
Saadi
  • 2,211
  • 4
  • 21
  • 50