Question

If my application is in Arabic culture then DateTime.UtcNow gives us arabic clander datetime like "13/05/1435 09:40:45 ص" but i need it in en-US what ever culture is used by my user.

When i am enforce to convert this date to us culture it gives me an error. what is the better way to get en-US datetime even in arabic culture like this "14/03/2014 09:40:45 AM".

var us = DateTime.Now.ToString("dd/MM/yy HH:mm:ss tt",
            new System.Globalization.CultureInfo("en-US"));

            string st = us.ToString();

            DateTime ddt = Convert.ToDateTime(st,
            new System.Globalization.CultureInfo("en-US"));

When converting from st to DateTime Again in en-US When Application is in Arabic Culture it throw error. enter image description here

Mr @lastr2d2

Thanks in advance.

Était-ce utile?

La solution

Is this what you excepted?

var ar = DateTime.Now.ToString("dd/MM/yy HH:mm:ss tt",
            new System.Globalization.CultureInfo("ar-AE"));
// 14/03/14 06:14:34 ص
var us = DateTime.Now.ToString("dd/MM/yy HH:mm:ss tt",
            new System.Globalization.CultureInfo("en-US"));
// 14/03/14 06:14:44 AM

--Edit

And you can get the datetime instance by DateTime.ParseExact :

var datetime = DateTime.ParseExact(us,"dd/MM/yy HH:mm:ss tt",
            new System.Globalization.CultureInfo("en-US"));

Autres conseils

The reason you are getting an exception that the string is not recognized as a valid DateTime is because you have explicitly specified the format when formatting to string but have not when you parse. 14/03/14 is ambiguous (which one is the year, which one is the month?) so it can't parse.

You have two options, (1) don't explicitly state the format and allow the default which in most cases will be able to be parsed, or (2) explicitly state the format when parsing.

In general, parsing dates is hard and getting dates from a user is better handled by a date control. Parsing dates as part of an interchange (to storage, or network) is legitimate but in that case should be governed by international standards (ISO 8601) and not by language specific formats.

I'm wondering too if the issue is that you want to format with a Gregorian calendar and allow the language to be the language of the application, but if so, that's a different question...

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top