简体   繁体   中英

How to set DateTime format without converting to string

I have a Person class which has a date time property. An object of Person type is sent back as oData response. The response being json.

"FirstName": "Tim",
"LastName": "Sam",
"EmailID": "tim@xyz.com",
"CompanyName": null,
"CreatedDate": "2014-03-18T19:24:30.847"

A lot of help on web suggest using ToString and specifying a format. How to set the Date in mm/dd/yyyy without resorting to a change to string so that the same is seen in json?

Regards.

How to set the Date in mm/dd/yyyy without resorting to a change to string

The Date pass in jSon is a string so you can pass it as a string. Date is stored in number of tick and there is not format of data object format is just a representation. The mm for month would be MM .

string strDateForJson = dateTimeObject.ToString("MM/dd/yyyy");

Internally, all DateTime values are represented as the number of ticks (the number of 100-nanosecond intervals) that have elapsed since 12:00:00 midnight, January 1, 0001. The actual DateTime value is independent of the way in which that value appears when displayed in a user interface element or when written to a file. The appearance of a DateTime value is the result of a formatting operation. Formatting is the process of converting a value to its string representation, MSDN .

"How to set the Date in mm/dd/yyyy without resorting to a change to string"

You can't do that. A DateTime value is a numeric representation of a point in time, it doesn't contain any information about the format.

The format is decided when you convert it to a string to display it. If you don't convert it to a specific format, then the default formatting is used, which depends on the culture settings for the code where the conversion is done.

Also, the JSON standard doesn't have any Date type at all, so you actually can't put a DateTime value in a JSON string. Either you need to use a non-standard solution, or convert the DateTime value into a different type.

You can't. A DateTime is a DateTime , and that's that.

If you want to represent it as something else, you have to convert it to something else - say a string, for instance. That is why converting to string with a specific format is the recommended answer.

So although it is perhaps not the answer you would prefer, your solution is basically something like:

yourDate.ToString("MM/dd/yyyy");

In order to prevent yourself from issues in the future I would consider using string in the interfaces instead of DateTime (eg format is mm/dd/yyyy). On the client and server side you can then convert it in whatever format you need.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM