date format using CultureInfo wont work - c#

I am trying to change the default date format by the way below but the format wont change and there is no errors
I am excepting to get date in Arabic format. What I am getting now is the default system format date like this (12:00:00 03/01/2011) while I want to overwrite the system format date
Note: Working under oracle11g
TBNextDate.Text = Convert.ToDateTime(oraReder[4])
.ToString("hh:mm:ss dd/MM/yyyy", new CultureInfo("ar-AE"));

According to MSDN:
The provider parameter defines the pattern that corresponds to the standard format specifiers, as well as the symbols and names of date and time components.
When you specify a specific format like you do that does not include any name specifiers, the only thing the culture changes is the separator symbol (e.g. / or .)
If you want to use a date pattern specific to that culture, use a standard format string instead:
TBNextDate.Text = Convert.ToDateTime(oraReder[4]).ToString("d", new CultureInfo("ar-AE"));

Related

Using invariant culture with IFormatProvider in DateTime.ParseExact

In the First overload of ParseExact method
public static DateTime ParseExact (string s, string format, IFormatProvider provider);
according to Microsoft:
If format is a custom format pattern that does not include date or time separators (such as "yyyyMMddHHmm"), use the invariant culture for the provider parameter and the widest form of each custom format specifier. For example, if you want to specify hours in the format pattern, specify the wider form, "HH", instead of the narrower form, "H".
In particular if we use stander format pattern we could use any other cultures
what is the really purpose of using invariant culture and widest custom specifier if we use custom format pattern that does not include date or time separators if we use?
The purpose of InvariantCulture is to have a well-known way to format dates and numbers, that does not depend on the system or user locale.
You should use it every time you format something that is not meant to be parsed by humans. For example in a JSON or XML file you want to store the date in ISO format so there is no ambiguity. On the other hand if you display the date on the screen, you generally respect the user's choice of culture and display it in the preferred way.
If you use a custom format, then it would surely be good if the resulting string can be parsed back into the exact same date and time. In order to do that without separators you have to use fixed length strings for each component.
// omitting CultureInfo.InvariantCulture for brevity
var dt = new DateTime(2018,1,2,3,45,6);
dt.ToString("yyyyMMddHHmmss") // returns "20180102034506"
dt.ToString("yyyyMdHms") // returns "2018123456"
You can easily see that the second one is not unique, i.e. there are other dates which will return the same string. In order to avoid that you use the wider form of each component.
the real purpose of invariant culture is taken taken from a an answer in this question, as it describes it's purpose best:
Not all cultures use the same format for dates and decimal / currency
values.
This will matter for you when you are converting input values (read)
that are stored as strings to DateTime, float, double or decimal. It
will also matter if you try to format the aforementioned data types to
strings (write) for display or storage.
If you know what specific culture that your dates and decimal /
currency values will be in ahead of time, you can use that specific
CultureInfo property (i.e. CultureInfo("en-GB")). For example if you
expect a user input.
The CultureInfo.InvariantCulture property is used if you are
formatting or parsing a string that should be parseable by a piece of
software independent of the user's local settings.
To sum this up, the invariant culture will help with conversions be a string stored to float, decimal or asDateTime, it is here also to help when you are trying to format or parse a string that should be parseable by a piece of software independent of the user's local settings, as the quote said and that is what
widest custom specifier
means by that.

Transform between datetime formats

I am facing a problem in which I need to transform dates in a given input format into a target one. Is there any standard way to do this in C#?
As an example say we have yyyy.MM.dd as the source format and the target format is MM/dd/yyy (current culture).
The problem arises since I am using a parsing strategy that gives priority to the current culture and then if it fails it tries to parse from a list of known formats. Now say we have two equivalent dates one in the source culture above (2015.12.9) and the other in the current culture (9/12/2015). Then if we attempt to parse this two dates the month will be 12 for the first case and in the second will be 9, so we have an inconsistency (they were supposed to mean be the same exact date).
I believe that if existing it should be something as
DateTime.Convert(2015.12.9, 'yyyy/MM/dd', CultureInfo.CurrentCulture).
Any ideas?
EDIT:
Thank you all for your ideas and suggestions, however the interpretation most of you gave to my question was not quite right. What most of you have answered is a direct parse in the given format and then a conversion to the CurrentCulture.
DateTime.ParseExact("2015.12.9", "yyyy.MM.dd", CultureInfo.CurrentCulture)
This will still return 12 as month, although it is in the CurrentCulture format. My question thus was, is there any standard way to transform the date in yyyy.MM.d to the format MM/dd/yyy so that the month is now in the correct place and THEN parsed it in the target culture. Such function is likely to be unexisting.
DateTime.ParseExact is what you are looking for:
DateTime parsedDate = DateTime.ParseExact("2015.12.9", "yyyy.MM.d", CultureInfo.InvariantCulture);
Or eventualy DateTime.TryParseExact if you're not confident with input string.
I know it's late but I try to explain little bit deep if you let me..
I am facing a problem in which I need to transform dates in any format
to a target one.
There no such a thing as dates in any format. A DateTime does not have any implicit format. It just has date and time values. Looks like you have a string which formatted as date and you want to convert another string with different format.
Is there any standard way to do this in C#?
Yes. You can parse your string with DateTime.ParseExact or DateTime.TryParseExact first with specific format to DateTime and then generate it's string representation with a different format.
As an example say we have yyyy.MM.dd as the source format and the
target format is MM/dd/yyy (current culture).
I didn't understand what is the meaning of current culture in this sentences and I assume you want yyyy not yyy, but you can generate it as I described above like;
string source = "2015.12.9";
DateTime dt = DateTime.ParseExact(source, "yyyy.MM.d", CultureInfo.InvariantCulture);
string target = dt.ToString("MM/dd/yyyy", CultureInfo.InvariantCulture); // 12/09/201
The problem arises since I am using a parsing strategy that gives
priority to the current culture and then if it fails it tries to parse
from a list of known formats.
Since you didn't show any parsing strategy and there is no DateTime.Convert method in .NET Framework, I couldn't any comment.
Now say we have two equivalent dates one in the source culture above
(2015.12.9) and the other in the current culture (9/12/2015). Then if
we attempt to parse this two dates the month will be 12 and in the
second will be 9, so we have an inconsistency.
Again.. You don't have DateTime's. You have strings. And those formatted strings can't belong on any culture. Sure all cultures might parse or generate different string representations with the same format format a format does not belong any culture.
I assume you have 2 different string which different formatted and you wanna parse the input no matter which one it comes. In such a case, you can use DateTime.TryParseExact overload that takes string array for all possible formats as a parameter. Then generate it's string representation with MM/dd/yyy format and a culture that has / as a DateSeparator like InvariantCulture.
string s = "2015.12.9"; // or 9/12/2015
string[] formats = { "yyyy.MM.d", "d/MM/yyyy" };
DateTime dt;
if (DateTime.TryParseExact(s, formats, CultureInfo.InvariantCulture,
DateTimeStyles.None, out dt))
{
Console.WriteLine(dt.ToString("MM/dd/yyyy", CultureInfo.InvariantCulture));
}
The Simple and Best way to do it is Using .ToString() Method
See this code:
DateTime x =DateTime.Now;
To Convert This Just Write like This:
x.ToString("yyyyMMdd")//20151210
x.ToString("yyyy/MM/dd)//2015/12/10
x.ToString("yyyy/MMM/dd)//2015/DEC/10 //Careful About M type should be capital for month .
Hope helpful

convert system date to M/d/yyyy format irrespective of system format using C#

How can I get today's date in M/d/yyyy format irrespective of system format of date using C#?
DateTime.Now.Tostring('M/d/yyyy')
is working only if the system date is in format dd/MM/yyyy or M/dd/yyyy but is not working in case yyyy-MM-dd format.
Eg:
if system date is 2013-06-26 then DateTime.Now.Tostring('M/d/yyyy') is converting the date into 06-26-2013 but not in 06/26/2013
Use CultureInfo.InvariantCulture to enforce / as date separator:
DateTime.Now.ToString("M/d/yyyy", CultureInfo.InvariantCulture)
Ideone
Looks like you just need to use CultureInfo.InvariantCulture as a second parameter in your .ToString method.
Console.WriteLine(DateTime.Now.ToString("M/d/yyyy", CultureInfo.InvariantCulture));
Using the invariant culture is the correct solution if you always want the same DateTime to produce the exact same string on multiple systems (or even on the same system due to culture changes). However, be aware that if this is user-visible, you're giving up the possibility of internationalization (for instance, if you display day or month names, they will be in English regardless of what language the user speaks). To only ensure that slashes are not replaced with another date separator, use single quotation marks:
DateTime.Now.Tostring("M'/'d'/'yyyy");
Edit:
Also, if your users are using different date formats, there's a good chance they're also using different time zones. If this DateTime needs to make sense across multiple systems, consider using DateTime.UtcNow. This will also protect you against potential bugs due to a user changing their time zone (when travelling, say) or daylight saving/summer time beginning/ending. If you're just displaying the string to the user at the current instance and not persisting it, DateTime.Now is probably what you want. In that case, however, I'd question why you're trying to mess with the format they've chosen.
Like this:
DateTime.Now.Tostring("M'/'d'/'yyyy");
The apostrofe forces the ToString() method to use the delimiter that you specified.
However, I would let the user choose a culture and use that cultures default formatting instead.

DateTime format not proper

i am trying to format the date to this format. 01/20/2013 02:30PM EDT, using this
LastModified.ToString("MM/dd/yyyy HH:mmtt");
but the result is coming like this
01-20-2013 02:30PM dont know why it is showing '-' instead '/'.
Also, for timezome, it seems there is only format available like +02:00. But I want timezone as string, i could not find any format for this, how can I get is as string like EDT/PST/IST etc?
From the MSDN page on custom date and time format strings:
The "/" custom format specifier represents the date separator, which is used to differentiate years, months, and days. The appropriate localized date separator is retrieved from the DateTimeFormatInfoDateSeparator property of the current or specified culture.
If you want it to definitely use /, you should either use the invariant culture, or quote the slash ("MM'/'dd'/'yyyy hh':'mmtt"). Note that I've quoted the time separator as well, as that can vary by culture too. I've also changed it to use the 12 hour clock, as per Arshad's answer.
When using a custom date/time format, you should probably use the invariant culture anyway. (For example, it seems odd to use a UK culture to format the string in a US-centric way - today would normally be represented as 02/05/2013 in the UK, not 05/02/2013.)
In terms of a time zone specifier - I don't know any way to use the time zone abbrevation within date/time formatting. I would personally advise against using abbreviations anyway, as they can be ambiguous and confusing. I can't see anything within TimeZoneInfo which even exposes that information for you to manually add it.
(It's possible that in Noda Time we'll support formatting with the abbreviation, but probably not parsing, precisely because of the ambiguity.)
i have found one mistake is that ,HH means time in 24 HRS format. You can try
string date = "01/20/2013 02:30PM";
DateTime dtTime;
if (DateTime.TryParseExact(date, "MM/dd/yyyy hh:mmtt",
System.Globalization.CultureInfo.InvariantCulture,
System.Globalization.DateTimeStyles.None, out dtTime))
{
Console.WriteLine(dtTime);
}
Formatting of DateTime is influenced by your Culture and your format string. Your current culture (Thread.CurrentThread.CurrentCulture) uses the - as the default seperator of your date components.
The Culture of India uses - and since you are from Inda, it would make sence (see: http://en.wikipedia.org/wiki/Date_and_time_notation_in_India)
Two options:
Choose a correct Culture which uses the / by default as seperator. For example: LastModified.ToString("MM/dd/yyyy HH:mmtt", new CultureInfo("en-US"));
Or reformat your format string with the escape character \. For example: For example: LastModified.ToString("MM\/dd\/yyyy HH:mmtt");
See also: http://msdn.microsoft.com/en-us/library/8kb3ddd4.aspx

Converting dates to internationalize format

I am reading the date from a field, and the date is already converted into the international format, thus it comes as, "مارس 12، 2012، 09:28 عصر", after reading the value i wish to extract the date out of the string. Like with English date strings we can use, new Date(dateString), is there a way to extract date in the localized format using the localized string.
Something that would work like,
var dateObject = new Date("مارس 12، 2012، 09:28 عصر"); and give me the dateObject.
Sorry for not able to provide more information about the problem, thanks in advance.
The Date.Parse and Date.TryParse methods will accept an instance of CultureInfo to let you parse these strings if they correspond to standard formats in a non-English culture.
Have you considered using CultureInfo? This may provide direction.
Here is documentation on the CultureInfo class.
"way to extract date in the localized format using the localized string":
myDate.ToString("date", new CultureInfo("ar-SA")); //arabic
To do this in US English:
myDate.ToString("date", new CultureInfo("en-US"));

Categories