C# Converting to date from inconsistent string - c#

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.

Related

DateTime being weird

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.

convert string in unknown format to date in c#

I have searched stackoverflow for an answer but no luck. I am developing a windows application and I have some strings in different date formats,
eg.
dd/MM/yyyy
MM/dd/yyyy
MM-dd-yyyy
dd-MM-yyyy
dd/MM/yyyy hh:mm::ss
MM/dd/yyyy hh:mm::ss
etc...
But I need to convert in to a common format - dd/MM/yyyy. The application can run in any windows machines in different culture.
What is the correct way to do it?
EDIT: One more thing I may not know what the format of incoming string.
Thanks in advance.
Use DateTime.ParseExact with the different patterns as formats.
If after parsing you really need to use a string representation, use the ToString method of the DateTime with the explicit format that you're interested in (so that it is culture-invariant). It's better however to keep the DateTime because this is format-agnostic.
You could distinguish between those formats that use different separators (i.e. "/" vs "-"). But how would you know if date such as 10/11/2010 represents 10th of November or 11th of October? If one number is not bigger than 12, there is no reliable way to do this without knowing an exact format.
As others have pointed out, if you do know the exact format, then you can use DateTime.ParseExact.
If you are processing some import file with a lot of dates in the same unknown format, you could try different formats and hope there is exactly one that doesn't give format errors.
Or to put it another way: split the "dates" into three numbers and check the range of values for each of those numbers. Values > 1900 will be years. If you find values from 1 to 31, those will be days.
Values from 1 to 12 might be months, but could also be days. Try and identify each of the parts.
The best way is to ask the supplier of those dates for the format.
To run this program on different culture, i think you should creat a function to indentify the culture of this string format and then use Datetime.Parse

Parsing datetime in textbox

I have datetime in one simple textbox. The format of the textbox's value can be anything like DD/MM/YYYY or MM/DD/YYYY. I want to parse this using DateTime.Parse(string). Currently for some dates it works and for others it throws Exception. How do I handle this? How do I make sure that no matter what format is provided it always parses correct (as long as it is valid date)?
Thanks in advance :)
EDIT
As there is no fix answer to it I modify my question to ask how do I convert it to MM/DD/YYYY? What should I provide in IFormatProvider of DateTime.Parse?
DateTime needs to know how to parse the date otherwise it won't know whether 05/07/2011 is the 5th July or the 7th May. Wouldn't it be better to use a calendar control to remove this ambiguity?
I suggest using a fixed format. You may even allow your users to select the format they want to use. But you absolutely need to know the format. Then you could use DateTime.TryParseExact. For instance, what would 01/03/2011 mean? It could be mm/dd/yyyy or dd/mm/yyyy. You really need to be explicit about this.
I came here to figure out if I can find a better solution than mine.
I already saw some of this solution propose here in other post and google. What IMHO works better is follow:
DateTime date;
bool isDate = (DateTime.TryParseExact(txtbxDATETIME.Value,
"yyyy'/'MM'/'dd",
CultureInfo.InvariantCulture,
DateTimeStyles.None,
out date));
//possible use:
DateTime someDATEorVAr = (isDate) ? date : DateTime.Now;
Hope somebody find this useful
That parsing problem can be solved by using the TryParse(String, IFormatProvider, DateTimeStyles, DateTime) variant so that culture info (most commonly I use CultureInfo.CurrentCulture) can be passed to it and thus removing the ambiguity.
DateTime.TryParse
Vijay

How to Convert date into MM/DD/YY format in C#

In My Asp.net webpage I need to display today's date into one of the textbox , so in my form load I wrote the following code
textbox1.text = System.DateTime.Today.ToShortDateString();
this line is giving me date like 1/7/09 but I want date like 01/07/09 , Is there anyway I can conver this date into mm/dd/yy format in C#?
DateTime.Today.ToString("MM/dd/yy")
Look at the docs for custom date and time format strings for more info.
(Oh, and I hope this app isn't destined for other cultures. That format could really confuse a lot of people... I've never understood the whole month/day/year thing, to be honest. It just seems weird to go "middle/low/high" in terms of scale like that.)
DateTime.Today.ToString("MM/dd/yy")
Look at the docs for custom date and time format strings for more info.
(Oh, and I hope this app isn't destined for other cultures. That format could really confuse a lot of people... I've never understood the whole month/day/year thing, to be honest. It just seems weird to go "middle/low/high" in terms of scale like that.)
Others cultures really are a problem. For example, that code in portugues returns someting like 01-01-01 instead of 01/01/01. I also don't undestand why...
To resolve that problem i do someting like this:
IFormatProvider yyyymmddFormat = new System.Globalization.CultureInfo(String.Empty, false);
return date.ToString("MM/dd/yy", yyyymmddFormat);
Have you tried the following?:
textbox1.text = System.DateTime.Today.ToString("MM/dd/yy");
Be aware that 2 digit years could be bad in the future...
Look into using the ToString() method with a specified format.
See, here you can get only date by passing a format string.
You can get a different date format as per your requirement as given below for current date:
DateTime.Now.ToString("M/d/yyyy");
Result : "9/1/2016"
DateTime.Now.ToString("M-d-yyyy");
Result : "9-1-2016"
DateTime.Now.ToString("yyyy-MM-dd");
Result : "2016-09-01"
DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss");
Result : "2016-09-01 09:20:10"
For more details take a look at MSDN reference for Custom Date and Time Format Strings

datetime.parse and making it work with a specific format

I have a datetime coming back from an XML file in the format:
20080916 11:02
as in
yyyymm hh:ss
How can I get the datetime.parse function to pick up on this? Ie parse it without erroring?
DateTime.ParseExact(input,"yyyyMMdd HH:mm",null);
assuming you meant to say that minutes followed the hours, not seconds - your example is a little confusing.
The ParseExact documentation details other overloads, in case you want to have the parse automatically convert to Universal Time or something like that.
As #Joel Coehoorn mentions, there's also the option of using TryParseExact, which will return a Boolean value indicating success or failure of the operation - I'm still on .Net 1.1, so I often forget this one.
If you need to parse other formats, you can check out the Standard DateTime Format Strings.
Thanks for the tip, i used this to get my date "20071122" parsed, I needed to add datetimestyles, I used none and it worked:
DateTime dt = DateTime.MinValue;
DateTime.TryParseExact("20071122", "yyyyMMdd", null,System.Globalization.DateTimeStyles.None, out dt);

Categories

Resources