Detecting the date format from a date string - c#

In my application I am having the possibility of getting date in two formats "dd/MM/yyyy" and "MM/dd/yyyy", and I want to have both date formats in "dd/MM/yyyy" format, I tried using DateTime.TryParseExact
string date = "12/21/2017";
DateTime dt;
if(!DateTime.TryParseExact(date, "MM/dd/yyyy", CultureInfo.InvariantCulture, DateTimeStyles.None, out dt))
{
DateTime.TryParseExact(date, "dd/MM/yyyy", CultureInfo.InvariantCulture, DateTimeStyles.None, out dt);
}
Console.WriteLine(dt.ToString());
My problem is that, my code works fine and if I have the date input like this 12/21/2017 (MM/dd/yyyy) and converts the date to 21/12/2017 (dd/MM/yyyy) but does not works if the date is like this 11/10/2017 which may be (MM/dd/yyyy) or (dd/MM/yyyy) it gives 10/11/2017 by considering the date format as (MM/dd/yyyy).
Is there any way to get the date format from the date so that I can use ParseExact to parse the date to (dd/MM/yyyy) format, or is there any way to convert the date formats which may be (MM/dd/yyyy) or (dd/MM/yyyy) to (dd/MM/yyyy).
Edit
Based on the conversation with you, I got that it is ambiguous in certain dates, I am going to ask the Front End team to give DateTime object rather than a date string. Thank you so much.

Related

TryParseExact doesn't work on string with date and time while format include only date format

Any idea why when i have time "00:00:00" in my string this does't work ?
DateTime.TryParseExact("01/06/2015 00:00:00", "dd/MM/yyyy", CultureInfo.InvariantCulture, DateTimeStyles.None, out tempDate)
While when i'm doing this it works Ok:
DateTime.TryParseExact("01/06/2015", "dd/MM/yyyy", CultureInfo.InvariantCulture, DateTimeStyles.None, out tempDate)
Any help will be much appreciated!
Thanks
From documentation;
Converts the specified string representation of a date and time to its
DateTime equivalent using the specified format, culture-specific
format information, and style. The format of the string representation
must match the specified format exactly.
For your second example they match, but in first example, they don't.
Use dd/MM/yyyy HH:mm:ss format instead.
string s = "01/06/2015 00:00:00";
DateTime dt;
if(DateTime.TryParseExact(s, "dd/MM/yyyy HH:mm:ss", CultureInfo.InvariantCulture,
DateTimeStyles.None, out dt))
{
// Successfully parsing
}
More information at;
Custom Date and Time Format Strings
Unfortunately, I tried the answer and it didn't work.
It turns out that there was a space character at the beginning of the date string I was trying to ParseExact. (e.g. " 20/08/2019")
So try a close examination of your date string and make sure there's no hidden characters or space characters you didn't spot

ParseExact inverse my day and month

my code below throw an exception as invalid date time. the error occur after i publish it to my server. working find at my developing PC
string str = "27-07-2015 6:15 pm";
DateTime dt = Convert.ToDateTime(DateTime.ParseExact(str, "dd-MM-yyyy h:mm tt", null).ToString("dd-MM-yyyy hh:mm tt"));
it takes '27' as month and '7' as day.
what i did to solve the problem:
i already update the datetime format on that server to dd-MM-yyyy
i double checked the capital and small letter of the date time format.
change the 'null' to 'CultureInfo.InvariantCulture'
change 'pm' to 'PM', 'tt' to 'TT'
read through all the resources i could find on google and stackoverflow, nothing's help.
am i missing something here? i know i did... :(
As #Rawling correctly noted, you're parsing the datetime twice: first, using your custom formatting, and second, using the system's default formatting.
This is silly - you already have the DateTime from the ParseExact method:
string str = "27-07-2015 6:15 pm";
var dt = DateTime.ParseExact(str, "dd-MM-yyyy h:mm tt", null);
That's it, you're done. No need to convert to string again, and parse that once more (and even worse, using the same custom formatting to do the ToString, so the subsequent Convert.ToDateTime is bound to fail anywhere that's not the default datetime formatting).
There are a few possibilities;
Let's analyze your DateTime.ParseExact(str, "dd-MM-yyyy h:mm tt", null) part first. This will be parsed your 27-07-2015 6:15 pm string successfully if;
Your CurrentCulture's TimeSeparator is : and
Your CurrentCulture's PMDesignator is PM (not empty string)
If both are okey, you have successfully parsed a DateTime.
After that, you generate it's textual representation with dd-MM-yyyy hh:mm tt format. And that's still depends on your CurrentCulture, your result might have PM or not. For both case, there is no guaranteed to parse your string with Convert.ToDateTime method because it will be parsed your string only if it is a standard date and time format of your CurrentCulture.
On the other side, what you do doesn't make sense to me. You parse your string first, then you generate string representation of it, then you try to parse this string again. Doesn't make sense, right?
I strongly suspect you just need;
string str = "27-07-2015 6:15 pm";
DateTime dt = DateTime.ParseExact(str, "dd-MM-yyyy h:mm tt", CultureInfo.InvariantCulture);

Can not Parse string to DateTime in Windows Phone 7

I am trying to convert the string to DateTime. But I can not convert.
DateTime dt = DateTime.Parse("16/11/2014", CultureInfo.InvariantCulture);
Console.WriteLine("Date==> " + dt);
The error is FormatException.
My input time format is "dd/MM/yyyy".
Please let me any idea to resolve my problem.
Given that you know your input format, you should specify it with `ParseExact:
DateTime dt = DateTime.ParseExact(text, "dd/MM/yyyy",
CultureInfo.InvariantCulture);
I would always recommend being as explicit as you can be about date/time formats. It makes your intention very clear, and avoids the possibility of getting months and days the wrong way round.
As Soner has stated, CultureInfo.InvariantCulture uses MM/dd/yyyy as its short date pattern, as you can validate with:
Console.WriteLine(CultureInfo.InvariantCulture.DateTimeFormat.ShortDatePattern)
As a mild plug, you might want to consider using my Noda Time project for your date/time handling - aside from anything else, that allows you to treat a date as a date, rather than as a date and time...
Because InvariantCulture doesn't have dd/MM/yyyy as a standard date and time format, but it has MM/dd/yyyy as a standard date and time format.
That's why it thinks your string is MM/dd/yyyy format, but since there is no 16 as a month in Gregorian calender, you get FormatException.
Instead of that, you can use DateTime.TryParseExact method to specify exact format like;
string s = "16/11/2014";
DateTime dt;
if(DateTime.TryParseExact(s, "dd/MM/yyyy", CultureInfo.InvariantCulture,
DateTimeStyles.None, out dt))
{
}

conversion from ddmmyyyy to mmddyyy

This is giving an exception:
String was not recognized as a valid DateTime.
string format = "MM/dd/yyyy hh:mm:ss.fff";
string dt_db1 = DateTime.ParseExact(txtTenureFrom.Text, "dd/MM/yyyy",
CultureInfo.InvariantCulture)
.ToString("MM/dd/yyyy", CultureInfo.InvariantCulture);
DateTime d1 = DateTime.ParseExact(dt_db1, format, CultureInfo.InvariantCulture);
You didn't specify the input data, but the first part looks inconsistent with the second.
You start with a date value you expect to be in dd/MM/yyyy format, without a time component.
You convert it to a date value in MM/dd/yyyy format, still without out a time component.
You then try to parse it again in MM/dd/yyyy hh:mm:ss.fff format, expecting a time component to somehow be introduced in the string???
Where do you expect the time to magically come from?

Converting dd/mm/yyyy formatted string to Datetime [duplicate]

This question already has answers here:
Converting a String to DateTime
(17 answers)
Closed 9 years ago.
I am new to DotNet and C#. I want to convert a string in mm/dd/yyyy format to DateTime object. I tried the parse function like below but it is throwing a runtime error.
DateTime dt=DateTime.Parse("24/01/2013");
Any ideas on how may I convert it to datetime?
You need to use DateTime.ParseExact with format "dd/MM/yyyy"
DateTime dt=DateTime.ParseExact("24/01/2013", "dd/MM/yyyy", CultureInfo.InvariantCulture);
Its safer if you use d/M/yyyy for the format, since that will handle both single digit and double digits day/month. But that really depends if you are expecting single/double digit values.
Your date format day/Month/Year might be an acceptable date format for some cultures. For example for Canadian Culture en-CA DateTime.Parse would work like:
DateTime dt = DateTime.Parse("24/01/2013", new CultureInfo("en-CA"));
Or
System.Threading.Thread.CurrentThread.CurrentCulture = new CultureInfo("en-CA");
DateTime dt = DateTime.Parse("24/01/2013"); //uses the current Thread's culture
Both the above lines would work because the the string's format is acceptable for en-CA culture. Since you are not supplying any culture to your DateTime.Parse call, your current culture is used for parsing which doesn't support the date format. Read more about it at DateTime.Parse.
Another method for parsing is using DateTime.TryParseExact
DateTime dt;
if (DateTime.TryParseExact("24/01/2013",
"d/M/yyyy",
CultureInfo.InvariantCulture,
DateTimeStyles.None,
out dt))
{
//valid date
}
else
{
//invalid date
}
The TryParse group of methods in .Net framework doesn't throw exception on invalid values, instead they return a bool value indicating success or failure in parsing.
Notice that I have used single d and M for day and month respectively. Single d and M works for both single/double digits day and month. So for the format d/M/yyyy valid values could be:
"24/01/2013"
"24/1/2013"
"4/12/2013" //4 December 2013
"04/12/2013"
For further reading you should see: Custom Date and Time Format Strings
use DateTime.ParseExact
string strDate = "24/01/2013";
DateTime date = DateTime.ParseExact(strDate, "dd/MM/yyyy", null)
DateTime.ParseExact
null will use the current culture, which is somewhat dangerous. Try to supply a specific culture
DateTime date = DateTime.ParseExact(strDate, "dd/MM/yyyy", CultureInfo.InvariantCulture)
You can use "dd/MM/yyyy" format for using it in DateTime.ParseExact.
Converts the specified string representation of a date and time to its
DateTime equivalent using the specified format and culture-specific
format information. The format of the string representation must match
the specified format exactly.
DateTime date = DateTime.ParseExact("24/01/2013", "dd/MM/yyyy", CultureInfo.InvariantCulture);
Here is a DEMO.
For more informations, check out Custom Date and Time Format Strings

Categories

Resources