C
C#3mo ago
cow

✅ How to Deserialize dd-MM-yyyy in System.Text.Json?

Hi guys. It seems I can happily deserialize a yyyy-MM-dd formatted date in C# using System.Text.Json However, when I try with a dd-MM-yyyy formatted date, I get the error: The JSON value could not be converted to System.DateTime How can I accept both date formats in System.Text.Json?
17 Replies
Angius
Angius3mo ago
You would need a custom converter I believe Or, if at all possible, make the JSON conform to the standard
cow
cow3mo ago
no it needs to be the role of the Server to accept both date formats, as the client side can be anyone from any country i'll look at the custom converter, thanks
Angius
Angius3mo ago
Well, sure, anyone from any country... but the standard is ISO 8601 And you are well within your right to reject anything that is not ISO 8601
leowest
leowest3mo ago
sure but do u write the client side? it would make more sense if the client site provides the same format when sending u can still show it to the client in their local format that is no issue. i.e.: if ur sending it as a string just format it, like your example ToString("yyyy-MM-dd")
cow
cow3mo ago
its just <input type="Date"> using whatever format the OS/Browser gives.... so dependent on the client OS's local datetime settings I guess
Angius
Angius3mo ago
The value of that is always ISO-8601
Angius
Angius3mo ago
cow
cow3mo ago
not for Safari 😅
leowest
leowest3mo ago
No description
No description
cow
cow3mo ago
im not sure why but always whenever i get a dd-MM-yyyy formatted date it's from a safari user
Angius
Angius3mo ago
How are you getting that value? Maybe you're doing some string -> datetime -> string conversion And it gets localized on the second arrow
cow
cow3mo ago
its an angular app, im just having a look through to see if i can anyone has configured some custom dateformatters or somethign Newtonsoft used to auto convert dates which was nice
Unknown User
Unknown User3mo ago
Message Not Public
Sign In & Join Server To View
michalgrzyska
michalgrzyska3mo ago
if this is an angular app, you probably are taking it from input with FormControl, can't you just map is there with new Date(control.value).toISOString() before sending to api? I know, it's an Angular response in C# chat, but still a possible solution to a problem
Unknown User
Unknown User3mo ago
Message Not Public
Sign In & Join Server To View
michalgrzyska
michalgrzyska3mo ago
this is my example (we dont know how the solutions looks), there is a possibility that new Date() is not enough, however I think we can both agree that this is a frontend responsibility to adjust to API standard rather than adjusting API for frontend code here
Unknown User
Unknown User3mo ago
Message Not Public
Sign In & Join Server To View