-1

We are creating a system with different locales. I can say all of the .net locales that can be found here : https://dotnetfiddle.net/e1BX7M

I googled a lot and datetime.parseexact or datetime.parse is only for one specific format, for example dd/mm/yyyy or mm/dd/yyyy.

Examples : When I use something like this

Date.Parse(Request.QueryString("asofdate"), CultureInfo.CurrentCulture)

and Request.QueryString("asofdate") format is dd/mm/yyyy, the system throws exception, otherwise when the format is mm/dd/yyyy works fine.

I also tried by using :

Date.Parse(Request.QueryString("asofdate"), CultureInfo.CurrentCulture)

How to handle all formats into one function? Do I have to use tryparse 10 times instead of using one integrated function from Date structure?

EDIT: The question : Is it possible to reduce code from tryparse (one format) tryparse ( second format) tryparse (third format) by using one line of code.

letsrock
  • 1
  • 2
  • What is `CultureInfo.CurrentCulture` set to? Can you link a specific culture to the DateTime format you're about to parse? If not, what is this date: `5/7/2019` representing? The 5th of July or the 7th of May? It won't even raise an exception and you'll end up with the wrong date. – Jimi Jul 23 '19 at 16:13
  • as i already mention, it could be en-us, bermuda, cayman islands, spain, france, or whatever .. all cultures are available here :https://dotnetfiddle.net/e1BX7M (already mention it) – letsrock Jul 23 '19 at 16:18
  • 1
    *Can you link a specific culture to the DateTime format you're about to parse?*. Meaning, you receive a string: `Request.QueryString(...)`. Does the `Request` object also provide the culture information needed to interpret this `DateTime` in string format? – Jimi Jul 23 '19 at 16:20
  • I would like to parse all datetime formats by using one function. For example dd/mm/yyyy, mm/dd/yyyy, etc. – letsrock Jul 23 '19 at 16:31
  • Is it possible to reduce code from tryparse (one format) tryparse ( second format) tryparse (third format) by using one line of code ? – letsrock Jul 23 '19 at 16:34
  • No, this is not possible because dates like 1/10/2019 are ambiguous. You need some out-of-band data to distinguish the different formats. – Dour High Arch Jul 23 '19 at 17:14

1 Answers1

0

seems we have a lack of information but assuming you are working on a Web API or a Controller, you can use the httpContext requestCulture feature


// Retrieves the requested culture
var feature = Request.HttpContext.Features.Get<IRequestCultureFeature>();
// information of the requested culture (assigned in the Accept-Language header
var culture = feature.RequestCulture.Culture;

Log($"current culture: {culture}")

//then

var parsedDate = DateTime.Parse(requestObject.dateValueFromJson, culture)
// warining this may cause an exception, so I suggest to use TryParse instead and handle when parsing fails.

Hope it helps.