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.
Related
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"));
I know that culture rules for dates/numbers is enough for an entire book, I think I have a simple question though..
Does using InvariantCulture basically mean that you explicitly define what culture the value (date/number/whatever) will be inputted/displayed as? And it overrides any other culture setting (such as the user agent's setting)?
If an app is built for an audience of one and only one culture, would it make sense to use InvariantCulture and define how you want values inputted/displayed each time?
Does using InvariantCulture basically mean that you explicitly define what culture the value (date/number/whatever) will be inputted/displayed as?
No. It's just a culture which is a bit like US English, except for a few things like currency sign. It's usually used to format/consume text which is to be understood or was produced by another computer rather than a human.
If an app is built for an audience of one and only one culture, would it make sense to use InvariantCulture and define how you want values inputted/displayed each time?
No, you would use the relevant CultureInfo for that culture. You could also explicitly define the format for dates etc, but that's an orthogonal concern. It may well be best to use one of the predefined standard formats for that culture, but if none of those meet your needs you can always be explicit.
InvariantCulture is Independent of any culture or any factor.
For example if you're using new CultureInfo("en-US") it will get you US English Culture(Which may not be actual US English Culture because OS gives you option to change these setting in Control Panel) it will return the modified version of Culture of "en-US" if any custom formatting applied to it.
In other words InvariantCulture will always gives you a Culture which can never be changed across Systems.
Let's assume you want to serialize some value(say double) and pass to another application or some other thread which is running in different culture leads to serious problems.
Consider the following code
Thread.CurrentThread.CurrentCulture = new CultureInfo("fr");
double source = 455.62d;
string serialized = source.ToString();//455,62 since `, is the decimal seperator` in "fr"
Thread t = new Thread((x) =>
{
double deserialized = double.Parse(((string)x));
Console.WriteLine(string.Format("Deserialized value is {0}", deserialized));//outputs 45562
});
t.CurrentCulture = new CultureInfo("en-US");
t.Start(serialized);
numbers matters more right? consider this string denotes AccountBalance?
Hope this helps
With specific regard to DateTime, the best advice I can give is to use CultureInfo.InvariantCulture for ParseExact and ToString when you have an exact format in mind. (You can also use it with Parse if you happen to know that your input format matches the invariant culture's formats, but I typically avoid this.)
Don't use the invariant culture when interacting with a user.
Keep in mind that the culture contains several items, including the ordering of day/month/year parts, the date and time part separator characters, the character encoding, and the language-specific names of the days of the week, months of the year, and abbreviations including am/pm.
Some examples of when you should use the invariant culture:
Files on disk, especially text files of a predefined format
External APIs, especially JSON or XML
Unit tests, unless you are specifically testing culture issues
Some examples of when you should use a specific culture such as en-US:
User Interface
Reports
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.
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
I want to display some rows of data on a web page where one column is a DateTime.
I want the date format to be displayed based on the current thread culture.
Right now, I'm doing this (dt is a DateTime):
string s = dt.ToString(Thread.CurrentThread.CurrentCulture.DateTimeFormat);
It's working well, however, on some culture, months and days are represented as only one digit (hours too), for example:
8/8/2011 8:57:59 AM
I would like the date to be displayed like this:
08/08/2011 08:57:59 AM
It would be easier to read (and prettier) when there's a list of rows.
I saw that there's a String.format method I could use, but that makes the current culture irrelevant.
Is there a way to achieve what I'm trying to do?
The solution provided here might be useful.
I see only a single solution - you should obtain the current culture display format, patch it so that it meets your requirement and finally format your DateTime value using the patched format string.
Make a custom culture.
Base it on the current thread culture.
Modify the settings you want to override.
Then either set it back into the thread as the culture or use it temporarily during the format operation.
We currently do this to format all dates in an internationally unambiguous form ddMMMyyyy where MMM is only English three-letter abbreviations, yet obey local numeric formatting rules ./, etc.
The relevant properties to override would be here.
If you want to show it based on the current culture, then what is the problem? If you want a specific format, you have to specify that.
string text = myDateTime.ToString("{0:[your format]}");
I believe this defaults to the server format - but what if you try specifying "u" as the format code which will put the year first then I think two digits.
You can use
String.Format("{0:dd/MM/yyyy hh:MM PM ", yourDatetime)
The date separator / (slash) and time sepatator : (colon) will be rewritten to characters defined in the current DateTimeFormatInfo.DateSeparator and DateTimeFormatInfo.TimeSeparator.
EDIT: Forgot to add object param needed to the string.format
using System.Globalization;
private static CultureInfo defaultCulture = new CultureInfo("nl-NL");
public static CultureInfo GetCurrentCulture()
{
List<CultureInfo> badCultures = new List<CultureInfo>();
badCultures.Add(new CultureInfo("en-US"));
if (badCultures.Contains(System.Threading.Thread.CurrentThread.CurrentCulture))
return defaultCulture;
return System.Threading.Thread.CurrentThread.CurrentCulture;
}