C
C#8mo 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
Angius8mo ago
You would need a custom converter I believe Or, if at all possible, make the JSON conform to the standard
cow
cowOP8mo 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
Angius8mo 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
leowest8mo 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
cowOP8mo 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
Angius8mo ago
The value of that is always ISO-8601
Angius
Angius8mo ago
cow
cowOP8mo ago
not for Safari 😅
leowest
leowest8mo ago
No description
No description
cow
cowOP8mo ago
im not sure why but always whenever i get a dd-MM-yyyy formatted date it's from a safari user
Angius
Angius8mo 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
cowOP8mo 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 User8mo ago
Message Not Public
Sign In & Join Server To View
michalgrzyska
michalgrzyska8mo 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 User8mo ago
Message Not Public
Sign In & Join Server To View
michalgrzyska
michalgrzyska8mo 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 User8mo ago
Message Not Public
Sign In & Join Server To View
Want results from more Discord servers?
Add your server