Davide Vignali
Davide Vignali

Reputation: 45

Web-Api datatime serialization issue

I have some issue with the return of a WEB API. This API processes the data and returns an object of type List <Dictionary <string, object >>. The problem is that when returning a date (datetime) the return format change depending on the server on which the site is installed.

For example I have these two cases:

Good Format

Bad Format

the first is the correct size, while the second is to wrong.

I have the following statement in the code that converts (should convert) the date to the desired format:

dict.Add(dc.Caption, ((DateTime)dr[dc.Caption]).ToString("yyyy-MM-dd HH:mm:ss"));

Can you help me?

Bye Davide

Upvotes: 0

Views: 79

Answers (1)

CodeCaster
CodeCaster

Reputation: 151604

The colon (:) in a DateTime format string does not always translate to a colon, it stands for "the time separator according to the current culture". See also MSDN: Custom Date and Time Format Strings.

You can see this in this code sample, using the Finnish culture, where the period is used as a time separator:

var finnishCulture = new CultureInfo("fi-FI");

Thread.CurrentThread.CurrentCulture = finnishCulture;

Console.WriteLine(DateTime.Now.ToString());
Console.WriteLine(DateTime.Now.ToString("HH:mm"));
Console.WriteLine(DateTime.Now.ToString(@"HH\:mm"));

This prints:

7.3.2017 15.58.47
15.58
15:58

Perhaps let WebAPI do the serialization for you, or if you're sure you want to serialize it yourself, escape the colon: \:.

Upvotes: 2

Related Questions