Asp-net web api displays date and time with letter T

data in the database looks like this:

2011-09-07 14:43:22.520 

But my web API is outputting data and replacing the space with the letter T

 2011-09-07T14:43:22.520 

I can replace the letter T with a space again in jquery, but can I fix this problem from the web API (do the web api output the source data?)

I also do not want miliseconds at the end. How can I get rid of them?

+7
javascript datetime asp.net-web-api
source share
1 answer

The format of how you see the date in the database usually does not matter, because it must be passed to .Net as a DateTime - not as a string . (If you store it as varchar in the database, you have more problems.)

ASP.Net WebAPI returns a value in the format defined by ISO8601 and RFC3339 . This is good, as it is a recognized machine-readable format. You probably don't want to change it.

If you really want to change it, you will need to implement the custom JSON.Net JsonConverter obtained from DateTimeConverterBase . Here are discussed here and here .

But instead, you should consider how you use the actual result in your client application. You mentioned jQuery, so I assume your consumer is JavaScript. In many browsers, the ISO8601 value that you have is already recognized by the JavaScript Date constructor, so you can simply do this:

 var dt = new Date("2011-09-07T14:43:22.520"); 

But this one will not work in all browsers . And Date doesn't have much formatting flexibility. So instead, you can consider a library like moment.js . With this you can do this:

 var m = moment("2011-09-07T14:43:22.520"); var s = m.format("YYYY-MM-DD HH:mm:ss"); // output: "2011-09-07 14:43:22" 

Note that the format string here corresponds to moment.js, not .NET. There are differences in case sensitivity. See the moment.js documentation for more details .

One more thing - since the value you provided has no Z at the end, and does not have an offset such as -07:00 , then I assume that it came from DateTime whos .Kind value DateTimeKind.Unspecified . You should know that when this is sent in JavaScript (or elsewhere in this case), there is no information about which time zone is presented. JavaScript will use the local time zone of the browser.

If this is not what you intended, then you need to store the UTC values ​​in your database and make sure they have DateTimeKind.Utc , so they end up serializing with Z at the end. JavaScript will normalize this to the time zone of the browser, but you will still be talking about the same point in time.

Alternatively, you can use the DateTimeOffset type, which will be serialized with a specific offset. JavaScript still normalizes this in the user time zone.

+31
source share

All Articles