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"));
Related
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.
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 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
normally i parse date like this way
DateTime.Parse()
DateTime.ParseExact()
i am in situation where user run exe and pass date as argument. so user can give date with various format like
dd/MM/yyyy
MM/dd/yyyy
dd-MM-yyyy
MM-dd-yyyy
yyyyMMdd
so i have to parse that date. when date format is yyyyMMdd then i am parisng date like this way DateTime.ParseExact(this.enddate, "yyyyMMdd", CultureInfo.InvariantCulture).ToString("yyyy-MM-dd");
so guide me what code i should write to parse date which work for any date format. thanks
I would recommend that you standardize on a single format. Otherwise you will run into ambiguous dates in cases where you have dates that can be parsed by different formats, but represent different dates in both
Ex:
dd-MM-yyyy
MM-dd-yyyy
what code i should write to parse date which work for any date format
As a technical answer, you can pass multiple formats to DateTime.TryParseExact() via a string array containing all acceptable formats.
Practically, though, the others have already pointed out that there is no way to tell the difference between months and days when the format isn't strictly enforced.
One possible solution is to have the user pass the date in as three separate arguments, each flagged with some kind of indicator such as /y2013 /m11 /d12 or maybe y:2013 m:11 d:12. You can even mash them together like /y2013/m11/d12. Then you can use Regular Expressions to parse out the parts, or even just plain old string manipulation.
There's no built in way to parse dates which work for ANY format. However, you can quite easily define your own format using DateTimeFormatInfo, letting you convert more or less any format to a proper date, as long as you know the format ahead of time.
In every major website you enter the date using comboboxes for day/month/year
or some datetime widget. So I don't see a reason to use a textbox. If you really
need to, add a tooltip or a watermark with the predefined format and force the
user to it.
Is there a way to use user's culture to localize the Range Validator for date? I am looking for a good way to validate date and avoiding to provide a fix format (e.g.: do a dd/mm/yyyy using Regular Expression Validator)
Use the Date.TryParseExact() method, consulting the documentation.
Use members of the returned My.Application.Culture.CurrentCulture.DateTimeFormat object, which is of class System.Globalization.DateTimeFormatInfo, to retrieve the date formats for the current culture (there are several formats for every culture, such as long format and short format...).
This will be something closest to what I want actually.
Getting user's language preference based on language settings:
userLanguage = Request.UserLanguages[0];
Get ShortDatePattern base on language:
new CultureInfo(userLanguage).DateTimeFormat.ShortDatePattern;
From here I will use the pattern to validate user's input and to display the required format on the page.