Reputation: 4747
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": "[email protected]",
"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.
Upvotes: 1
Views: 3437
Reputation: 700152
"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.
Upvotes: 1
Reputation: 19081
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");
Upvotes: 0
Reputation: 148110
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.
Upvotes: 0