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