How come
w.WriteLine(Program.RegisterList[i].DateTime);
Writes : 11/20/2013 01:46:31 PM
But
w.WriteLine(Convert.ToDateTime(Program.RegisterList[i].DateTime, CultureInfo.InvariantCulture).ToString());
Writes 20/11/2013 1:46:31 PM
? Isn't invariant culture supposed to make it MM/DD/YY? I would like to use the invariant culture method incase a date slips by in DD/MM/YY format.
Thanks!
Edit: I should mention Program.RegisterList[i].DateTime is a string.
Edit2:
MessageBox.Show("11/20/2013 01:46:31 PM");
MessageBox.Show(Convert.ToDateTime("11/20/2013 01:46:31 PM", CultureInfo.InvariantCulture).ToString());
w.WriteLine(Convert.ToDateTime(Program.RegisterList[i].DateTime, CultureInfo.InvariantCulture).ToString());
You confused yourself by writing code you can't understand anymore. A simple rewrite of that one honking statement:
string s = Program.RegisterList[i].DateTime;
DateTime dt = Convert.ToDateTime(s, CultureInfo.InvariantCulture);
w.WriteLine(dt);
Which should now make it obvious that you are not using InvariantCulture to display the date, it uses the default culture. Which on your machine puts the day first.
Always write readable code, it is not slower.
CultureInvariant only guarantees that the format won't change across cultures - it should not be used to display data, only to persist data. If you're concerned about how a string is displayed, you should use a specific culture that displays how you want. More from MSDN
Having said that, I'm not sure what you mean by a "date slipping by" in a different format. Are you reading a list of dates, and some are in different format? If so, I'm afraid CultureInvariant is not the answer.
Related
I'm trying to parse a file where I get my dates as string like those:
5/18/2020 8:38:32 AM
6/8/2021 10:11:42 PM
11/24/2021 9:21:54 AM
----
I tried to use a DateTime.TryParse on my string and test the "---" case in a if statement which work but it succeed to convert only the 6/8/2021 12:41:56 PM.
I tried to use TryParseExact and specify a date format but it seem that I should make a case months with one and two digits and same the days.
I guess there is something I'm not seeing or don't know.
Thanks for you help.
It is because you are probably on a culture other than en-US which those dates are formatted in. Use IFormatProvider parameter. ie:
void Main()
{
var dates = #"5/18/2020 8:38:32 AM
6/8/2021 10:11:42 PM
11/24/2021 9:21:54 AM
----";
foreach (string s in dates.Split('\n'))
{
if (DateTime.TryParse(s, new CultureInfo("en-US"), DateTimeStyles.None, out DateTime d))
{
Console.WriteLine(d);
}
}
}
Here is the .Net fiddle link.
EDIT: Note that the version on .Net fiddle is slightly different because of the older C# version there.
Without the exact details, I have to guess:
If he only can translate the 6/8 date, you may have the wrong locale settings (you have something like MM/dd/yyyy .... but this works only for the 8th of june, what you might get wrong with 6th of august)
If you use ParseExact, you can also provide a list of valid format strings.
EDIT
Cetins answer is correct. Additionally, the title of the post is a bit confusing, because the datetime string IS consistent (in the 'en-US' local settings)
#Cetin Basoz You are right, it was indeed a culture problem. Thank you!
#nabuchodonossor You are right about the datetime string ("----" apart) being consistent. What I wanted to say was that there is no every time two digits for the days or months which would not happen if the dates were something like 05/18/2020 and 06/08/2021. Sorry, I have a hard time being precise.
Basically,I am reading excel file where one of that columns has date format like : dd/MM/yyyy eg: 11/04/2016
When I am using DateTime.TryParse() to parse that string into datetime method TryParse() treated first numbers like month (number 11 in example above). However the same code running on the other computers will take the second number (04 in example above) as the month.
So my question is why there is a difference between them, what actually decide the behavior of TryParse method?
I think the main difference is in IFormatProvider (hard to say if I can't check some settings in target system), but I usually use other method to get proper DateTime object:
DateTime someDate = DateTime.ParseExact(myStringDate, "dd/MM/yyyy", System.Globalization.CultureInfo.InvariantCulture);
It always gives me what I want no matter how client environment is configured.
Hope this helps. :)
From DateTime.TryParse(String, DateTime) documentation:
Because the DateTime.TryParse(String, DateTime) method tries to parse
the string representation of a date and time using the formatting
rules of the current culture, trying to parse a particular string
across different cultures can either fail or return different results.
If a specific date and time format will be parsed across different
locales, use the
DateTime.TryParse(String, IFormatProvider, DateTimeStyles, DateTime)
method or one of the overloads of the TryParseExact method and provide
a format specifier.
That means your computers have different culture settings which is pointed in CurrentCulture property.
Looks like one computer's current culture have dd/MM/yyyy and the other computer's current culture have MM/dd/yyyy as a standard date and time format.
Since you are sure your values are always in dd/MM/yyyy format, I would use DateTime.ParseExact instead of Datetime.TryParse or DateTime.TryParseExact methods like;
var dt = DateTime.ParseExact(yourColumnValue, "dd/MM/yyyy", CultureInfo.InvariantCulture);
Or you can sets all computers current culture to like the first computer but remember, CultureInfo data is not a stable data that might be change in future with a windows update, .NET Framework version or OS version.
I want to parse string to time, the string can be "hh:mm tt", or "hh:mmtt"
"11:00am", "11:00 am", "13:00" "5:00AM" "6:00PM" , "6:00 pm", "6:00:01 pm" etc.
I wonder how to parse it correctly. My thought is to enumerate all the formats like below.
But I feel it is awkward and there must be a better way. thanks
DateTime ret = DateTime.MinValue;
DateTime.TryParse(timeStr, CURRENT_CULTURE_FORMATPROVIDER,Style1, out ret);
if(ret == DateTime.MinValue)
{
DateTime.TryParse(timeStr,CURRENT_CULTURE_FORMATPROVIDER,Style2, out ret);
}
if(ret == DateTime.MinValue)
{
DateTime.TryParse(timeStr,CURRENT_CULTURE_FORMATPROVIDER,Style3, out ret);
}
...
return ret;
Not really an answer but not fitting to comments: reject values that are not completely clear instead of potentially guessing wrong.
While it is very tempting to guess what actual value particular string represents it is very dangerous route. The chances of guessing value wrong are higher more input "formats" you accept.
If data coming from some computer-generated source - simply rejecting unexpected data is probably best option. Consider if asking for some fixed well known culture-insensitive format works (i.e. ISO8601 optionally with timezone)
If this data coming directly from user it may be better to immediately reject the data and let user re-enter date in more precise format. If possible - simply don't let user to pick and force particular format.
If you randomly guess values incorrectly users (if they care and have to use your tool often) will learn to type values in one very particular format and have verbal instructions to only use that (like "hours two spaces colon minutes, only add PM for values in afternoon")...
Note that only some cultures (in .Net sense) have AM/PM designator, so make sure to test your code against those too.
DateTime.TryParse seems to be working for your problem. Have a look
string myTime = "5:00AM";
DateTime dt = DateTime.Now;
DateTime.TryParse(ss, out dt);
I am trying to parse a date that is coming from a source as "02/11/2013"
In my application, I set the user's culture to either en-CA or en-FR, with their date format's being "dd/MM/yyyy" or "M/d/yyyy"
If I parse the date, and pass in the format, will this work or does it depend on which format I saved to the database?
if (DateTime.TryParseExact(dateString, Thread.CurrentThread.CurrentCulture.DateTimeFormat.ShortDatePattern, null, System.Globalization.DateTimeStyles.None, out dtResult))
{
dt = dtResult;
}
I can think properly right now so I need some clarification.
Me passing in the format of "dd/MM/yyyy" or "M/d/yyyy", does this format the date no matter what format the source is in, or is it me telling the datetime parse that the source will be in this format so use this?
What I am weary of is that someone is saving to the db in one format, and then a french person wants to read the date and their own format (yes I should be storing in utc).
ADO.NET is strongly typed; there are well known types for storing most data. In the case of dates, that would be DateTime in .NET and datetime in most database systems. If you ever need to worry about culture, then you're already doing it wrong, because you are passing the data around as a string rather than as a DateTime / datetime.
This then renders your concern here redundant:
What I am weary of is that someone is saving to the db in one format, and then a french person wants to read the date and their own format (yes I should be storing in utc).
because a DateTime / datetime has no notion of format - it is simply a date/time value. Any UI presentation / parsing of string data should be completely isolated and specific to the UI. Beyond the UI code you should (when talking about dates/times) be using DateTime / datetime exclusively.
Similarly, when storing an integer you should be using int.
If the date is stored only as "02/11/2013" without any other culture identifying information there is no way for you to know how to properly interpret it! You are absolutely right being worried that somebody with a en-FR culture might save a date to the database as "02/11/2013" meaning the 2nd of November and then somebody with an en-US culture might read that date and interpret it as the 11th of February.
You should only pass the current culture if you know that is relevant, meaning that you know the date string was generated using that culture.
A better approach is to NOT store dates like that in the first place. It's best to store the date in a format that includes timezone as well as format information such as the Internet Date/Time RFC 3339 format.
Or, if you can't, at least make sure to take the date and always convert it to say en-US culture before storing in the database and than pass that culture to the DateTime.Parse when reading from the database.
The .NET XML serialization code for dates can come in handy when serializing/deserializing dates in RFC 3339 format. See this SO post for more info..
I have a time field as such: 06:30 PM.
What formatting do I need so that it shows up as 6:30 PM.
I tried:
String.Format("{0:t}", data.PgTime)
but still getting 06:30 PM
Well, t is the standard format string for "short time pattern" - so it's being formatted according to the current culture's rules. For me, it would show "18:30" because that's the appropriate format for the UK.
You can either stick to the rules .NET knows about, or you can use a custom date and time format string to force a specific format, e.g.
string text = date.ToString("h:mm tt");
(Note that this is basically equivalent to string.Format("{0:h:mm tt}", date) but considerably simpler to read - I'd suggest only using composite formatting when you're really formatting more than one value.)
Usually that would not be a good idea though - it suggests that you know more about cultural rules than Windows / .NET, which is unlikely to really be the case. I'm sure you know more about how you personally like to format dates and times, but that's not the same as it being the standardized convention for your culture.
String.Format("{0:h:mm tt}", data.PgTime)
See also:
Custom Date and Time Format Strings on MSDN.