Convert english Date with parse exact - c#

I try to convert a english date to an german, but my format is not good.
Thread.CurrentThread.CurrentCulture = new CultureInfo("en-US");
DateTime currentCultureDate = DateTime.Now;
string format = "dd.MM.yyyy HH:mm:ss";
Console.WriteLine("Format: " + format);
Console.WriteLine("Original Date: " + currentCultureDate);
DateTime convertedDate = DateTime.ParseExact(currentCultureDate.ToString(), format, new CultureInfo("de-DE"));
Console.WriteLine("Converted Date: " + convertedDate);
FormatException.....

DateTime.ParseExact is used to create a DateTime from a string. You can pass a DateTimeFormat or CultureInfo which will be used to convert that string to DateTime.
The method does not convert it to a string in another CultureInfo, say de-DE. Therefore you can use DateTime.ToString:
string germanFormat = DateTime.Now.ToString("dd.MM.yyyy HH:mm:ss", new CultureInfo("de-DE"));

You are not doing what you say: Your code actually tries to parse the date in German format:
// This is German format
string format = "dd.MM.yyyy HH:mm:ss";
// This takes a date and parses it using the ABOVE FORMAT - which is German
DateTime convertedDate = DateTime.ParseExact(currentCultureDate.ToString(), format, new CultureInfo("de-DE"));
If you already have a DateTime you want to output in German format, you don't need ParseExact, but ToString:
string german = DateTime.Now.ToString(format, new CultureInfo("de-DE"));
A DateTime itself doesn't have any culture formatting attached. It is just a date and a time. Only when you output a DateTime, it somehow needs to be converted into a string and to do so, culture information is required. So the rule of thumb is:
If you get a string that represents a date and time value, you need to parse it into a DateTime, either using a fixed format and ParseExact or relying on the framework, passing the source culture information to Parse or TryParse.
If you have a DateTime and want to output it, you need to format it using ToString, providing either a fixed format string and culture information, or use ToString only for the current thread's culture.

Related

How to Convert date into String format to Date format in C#?

I am trying to convert this ("2019-09-09"(yyyy-MM-dd)) string into date format. I am using DateTime.ParseExact method, but it is not giving me the expected output.
string transactionDateFrom = "2019-09-09";
var provider = CultureInfo.InvariantCulture;
var c = DateTime.ParseExact(transactionDateFrom, "yyyy-MM-dd", provider);
But it shows output as (09/09/2019 12:12Am) I just need format like (yyyy-MM-dd) and it must be date format not string.
You should also provide format for ToString or whenever you use that, since right now you only use it for parsing.
You may also just edit the culture the following way:
CultureInfo culture = (CultureInfo) CultureInfo.CurrentCulture.Clone();
culture.DateTimeFormat.ShortDatePattern = "yyyy-MM-dd";
culture.DateTimeFormat.LongTimePattern = "yyyy-MM-dd";
You should either use DateTime.TryParseExact or use DateTime.TryParse specifying the appropriate CultureInfo.
(For E.g., the culture of the user.)
You can use DateTime.ParseExact method overloads and you can specify exact format and proper (that uses / as a DateSeparator) culture information.
Also be aware that the Difference between M and MM specifiers.
For single digit month numbers, MM specifier will generate month number with leading zero (like 09) but M specifier won't.
string strDate = "2019-09-28";
DateTime date = DateTime.ParseExact(strDate, "yyyy-MM-dd", System.Globalization.CultureInfo.InvariantCulture);
string Format = date.ToString("yyyy-MM-dd", CultureInfo.InvariantCulture);
OR
string strDate = "2019-9-28";
DateTime date = DateTime.ParseExact(strDate, "yyyy-M-dd", System.Globalization.CultureInfo.InvariantCulture);
string Format = date.ToString("yyyy-M-dd", CultureInfo.InvariantCulture);

How to convert date from one culture to another culture?

I have date with yy-MMM format in polish culture (pl-PL) and i want to convert that date in English (en-US)
Example
19-maj
Expected Output
19-may
Thanks in advance
If you have a string representing a datetime and you want to display the same information but in a different Culture then you could convert that string to a DateTime with the proper CultureInfo, then, once you get a datetime, you could output it in any format you like
string input = "19-maj";
CultureInfo ci = new CultureInfo("pl-PL");
DateTime dt = DateTime.ParseExact(input, "yy-MMM", ci);
string output = dt.ToString("yy-MMM", CultureInfo.InvariantCulture);
Console.WriteLine(output);

Storing date time in culture neutral format + C#

I accept date info from the user, via date picker. I need to store them in a culture neutral way. The problem I am facing is, if I store the date as per en-US format (based on calendar settings), namely 11/20/1990 it will fail to parse when the culture is en-GB.
And vice versa happens when culture is en-US, date stored as per UK format, dd/mm/yyyy refuses to parse. How do I store date info in a culture neutral way in a file so that, I get the date to work in both locations?
DateTime.TryParse(userEnteredValue, out result);
result.ToShortDateString(); //this is what I am doing
tried this code for invariant culture
string input = "20/10/1983";
DateTime userInput;
bool result = DateTime.TryParse(input, out userInput);
string invariantCulture = userInput.Date.ToString(CultureInfo.InvariantCulture);
DateTime storedValue;
result = DateTime.TryParse(invariantCulture, out storedValue);
tried this code with en-GB calendar settings, second statement DateTime.TryParse fails infact.
#Soner Gönül's answer is spot on if you are saving the dates to a database. However, you mention that you are looking to round-trip a DateTime to and from a file.
As the file is presumably a text file you'll need to write the DateTime in a culture neutral manner. You can do this by using the "O" format specified on the DateTime.ToString method. This will output a string representation that complies with ISO 8601. The resultant string can be parsed using DateTime.Parse without the need for culture information.
As an example:
string filename = #"c:\temp\test.txt";
string usDateString = "11/18/2014 12:32"; // MM/dd/yyyy
string ukDateString = "18/11/2014 12:33"; // dd/MM/yyyy
//I'm mimicking you getting the DateTime from the user here
//I'm assuming when you receive the date(s) from the front
//end you'll know the culture - if not then all bets are off.
DateTime usDate =
DateTime.Parse(usDateString, CultureInfo.GetCultureInfo("en-US"));
DateTime ukDate =
DateTime.Parse(ukDateString, CultureInfo.GetCultureInfo("en-GB"));
//write the dates to a file using the "o" specifier
File.AppendAllText(filename, usDate.ToString("o") + Environment.NewLine);
File.AppendAllText(filename, ukDate.ToString("o") + Environment.NewLine);
//read them back in as strings
string[] contents = File.ReadAllLines(filename);
foreach (var date in contents)
{
//prove we can parse them as dates.
Console.WriteLine(DateTime.Parse(date).ToString());
}
This creates a file with the contents:
2014-11-18T12:32:00.0000000
2014-11-18T12:33:00.0000000
and on my system (in the UK) it prints:
18/11/2014 12:32:00
18/11/2014 12:33:00
if I store the date as per en-US format...
Please stop! Looks like you try to save your DateTime values with their string representations.
A DateTime doesn't have any implicit format. It has just date and time values. String representations of them can have a format. Generate your insert queries and pass your DateTime values directly with parameterized way.
Please read;
Bad habits to kick : choosing the wrong data type
If you want to get string representations of your DateTime values with specific format, you can always use DateTime.ToString() method and it's overloads.
Your en-GB culture can parse MM.dd.yyyy (since you use / format specifier which replaces itself supplied culture DateSeparator) and en-US culture can parse MM/dd/yyyy as well.
But since you use .ToShortDateString() method, this represents your datetime based your CurrentCulture settings. As a solution, you can set this property which culture you want and ToShortDateString works based on it.
result = DateTime.TryParse(invariantCulture, out storedValue);
tried this code with en-UK calendar settings, second statement
DateTime.TryParse fails infact.
Because this DateTime.TryParse uses your CurrentCulture and since your invariantCulture variable is 10/20/1983 00:00:00, that means this is not a standard date and time format for your CurrentCulture.
There is no such a culture as en-UK by the way.
10/20/1983 00:00:00 is MM/dd/yyyy HH:mm:ss format. But en-GB culture doesn't have this format as a standard date and time format, that's why your method returns false.
As an alternative, you can use custom format strings like;
string s = "10/20/1983 00:00:00";
string format = "MM/dd/yyyy HH:mm:ss";
DateTime dt;
if (DateTime.TryParseExact(s, format, CultureInfo.GetCultureInfo("en-GB"),
DateTimeStyles.None, out dt))
{
Console.WriteLine(dt);
}
I bumped into this question and figured I'd bring in some other way nobody has mentioned yet:
DateTime.ToBinary() for serializing and DateTime.FromBinary(Int64) for deserialization.
What these do is the following:
ToBinary() returns a long which can be easily stored in a culture invariant way.
FromBinary(Int64) will return a DateTime object from the long parameter supplied.
(They even take the date time Kind property into consideration).
And here's some code to go with it:
DateTime d1l = DateTime.Now;
long dl = d1l.ToBinary();
DateTime d2l = DateTime.FromBinary(dl);
DateTime d1u = DateTime.UtcNow;
long du = d1u.ToBinary();
DateTime d2u = DateTime.FromBinary(du);
Console.WriteLine("Local test passed: " + (d1l == d2l).ToString());
Console.WriteLine("d2l kind: " + d2l.Kind.ToString());
Console.WriteLine("Utc test passed: " + (d1u == d2u).ToString());
Console.WriteLine("d2u kind: " + d2u.Kind.ToString());
And the console output:
Local test passed: True
d2l kind: Local
Utc test passed: True
d2u kind: Utc
I find this to be pretty neat!
String s = "24. 11. 2001";
d = DateTime.Parse(s, CultureInfo.CreateSpecificCulture("sk-SK"));
en-AU (English Austrailia): 24/11/2001
en-IA (English India): 24-11-2001
en-ZA (English South Africa): 2001/11/24
en-US (English United States): 11/24/2001
i suspect you prefer English (India) (en-IA).
But if you really can't decide what culture to use when converting dates to strings and vice-versa, and the dates are never meant to be shown to a user, then you can use the Invariant Culture:
String s = "11/24/2001" //invariant culture formatted date
d = DateTime.Parse(s, CultureInfo.InvariantCulture); //parse invariant culture date
s = d.ToString(CultureInfo.InvariantCulture); //convert to invariant culture string
I tried to figure out a solution via this approach, please let me know if its correct.
The code which I use is below.
For Saving date time I use ticks as below.
DateTime userInput;
bool result = DateTime.TryParse(this.dpSave.Text, out userInput);
if (result)
{
long ticks = userInput.Ticks;
System.IO.File.WriteAllText(#"D:\folder\Ticks.txt", ticks.ToString());
}
else
{
MessageBox.Show("Date time parse failed");
}
For loading it back, I use
if (System.IO.File.Exists(#"D:\folder\Ticks.txt"))
{
string contents = System.IO.File.ReadAllText(#"D:\Sandeep\Ticks.txt");
long ticks;
if (long.TryParse(contents, out ticks))
{
DateTime storedDateTime = new DateTime(ticks);
MessageBox.Show("Stored Date" + storedDateTime.ToShortDateString());
}
else
{
MessageBox.Show("Unable to obtain stored dates");
}
}
this seems to work, provided, I save using en-US culture and load using en-GB culture.
please let me know if this is the right approach!
a) Exchange data shall always be stored culture invariant (xml etc)
b)You've gotta to be careful with the terminology.
What you exactly mean is culture INVARIANT (and not 'culture neutral').
There are three types of cultures:
1) invariant
2) culture neutral (e.g. "en")
3) culture specific (e.g "en-US")
public DateTime getdate3()
{
CultureInfo Invc = CultureInfo.InvariantCulture; //culture
string cul = Thread.CurrentThread.CurrentCulture.Name;
CultureInfo us = new CultureInfo(cul);
string shortUsDateFormatString = us.DateTimeFormat.ShortDatePattern;//pattern
DateTime dt = Convert.ToDateTime(DateTime.Now);
TimeZoneInfo myZone = TimeZoneInfo.FindSystemTimeZoneById("India Standard Time"); //india zone
DateTime dateindia = TimeZoneInfo.ConvertTime(dt, myZone);
string dt1 = Convert.ToDateTime(dateindia).ToString(shortUsDateFormatString); //string format
}

How to Convert a Date String with Format "dd/MM/yyyy" to OS Current Culture Date Format

A string has the value in "dd/MM/yyyy" format like "04/10/2012". This should be converted to a Date w.r.t Current Culture of OS.
I have tried below string with Korean as Current Culture of OS in which date format is yyyy-MM-dd, my code is not getting correct Month value, it interchange the month value with day:
Input: "04/10/2012"
Output: 2012-04-10
Code:
DateTime DT;
string dt = "04/10/2012";
DateTimeFormatInfo DateInfo = CultureInfo.CurrentCulture.DateTimeFormat;
DT = Convert.ToDateTime(String.Format ("{0:"+DateInfo .ShortDatePattern +"}", dt.Trim ()), CultureInfo .CurrentCulture);
MessageBox.Show("Date: " + DT.ToShortDateString());
How I can fix that ?
It looks to me like you need to parse it with a fixed format, I think you are currently parsing it with a format other than "dd/MM/yyyy" and because the date is ambiguous (as in, month and day can be interchanged without causing invalid dates) the format is simply switching the month and day value. When you then go to output it, it looks reversed.
Use DateTime.ParseExact to force the parsing format and then use the built-in current culture sensitive string output methods on DateTime to get a formatted string:
var date = DateTime.ParseExact("04/10/2012", "dd/MM/yyyy", CultureInfo.InvariantCulture);
MessageBox.Show("Date: " + date.ToShortDateString()); // Assumes current culture is controlling format
Since your input string is in a fixed format, you should parse it in that format:
DateTime.ParseExact(dt, "dd/MM/yyyy", CultureInfo.InvariantCulture);
If you string has the format dd/MM/yyyy then you have to use DateTime.ParseExact with the specified format:
DateTime.ParseExact(dt, "dd/MM/yyyy", CultureInfo.InvariantCulture);
Anything else will try an interpret the string according to the current culture's rules - which, as you have found, will fail.
why not use ToShortDateTimeString()

Retaining MM/DD/YYYY format in String

I need to write date in MM/DD/YYYY format. From a Date Picker Control. I try to assign it to a DateTime variable. Before Writing it to a file I assign it to a string. I see the value stored in String variable is in DD/MM/YYYY format.
Below is assignment statement
DateTime startTime, endTime;
string startTimeDate = "";
startTime = Convert.ToDateTime(dpStartTime.Value.ToString("MM/dd/yyyy HH:mm"));
endTime = Convert.ToDateTime(dpEndTime.Value.ToString("MM/dd/yyyy HH:mm"));
startTimeDate = startTime.ToString("MM/dd/yyyy HH:mm");
startTimeDate = startTimeDate.Replace('-', '/');
I observe startTimeDate is stored as DD/MM/YYYY only. startTime is storing as MM/DD/YYYY format only. Please let me know if there is any other approach to correctly assign / convert the date values.
Thanks in Advance
Edit:
You are losing the original date in your Convert.DateTime() conversion, you have to apply the format string here as well e.g. using DateTime.ParseExact :
startTime = DateTime.ParseExact(dpStartTime.Value.ToString("MM/dd/yyyy HH:mm"),
"MM/dd/yyyy HH:mm",
CultureInfo.InvariantCulture);
Instead of using Convert.ToDateTime(), try to use DateTime.ParseExact(string s, string format, IFormatProvider provider) when you can ensure the datetime format and want to ignore the system settings. MSDN Reference for the DateTime.ParseExact() method can be found here
You're converting DateTime to string, then you're converting it again to DateTime using Convert class. You're not preserving the format here cause DateTime is format agnostic. And default ToString conversion (used by debugger) is in your cause MM/DD/YYYY.
I usually use String.Format, ex
String.Format("{0:d/M/yyyy HH:mm:ss}", dpStartTime.Value);
To format dates as strings.

Categories

Resources