Reputation: 1083
I know there is a lot of asked question here about DateTime
but I saw them all already and seems not to find the right solution for my case.
Here is my code:
return DateTime.ParseExact(partialDate + dtfi.DateSeparator + _baseDate.ToString(), "dd/MM/yyyy", new CultureInfo("en-us");
This is throwing me an Exception.
Here is the value of the variables:
string partialDate = "1/22";
string dtfi.DateSeparator = "/";
int _baseDate = 2004;
Upvotes: 0
Views: 1430
Reputation: 98750
Unfortunately, both answers are wrong.
So, we all agree your result string will be "1/22/2004"
. Before looking which formats exactly matches your characters, let's look at your string is a standard date and time format for en-US
culture or not.
DateTime.Parse("1/22/2004",
CultureInfo.GetCultureInfo("en-US")) // 22 January 2004 00:00:00
We have a DateTime
perfectly. But what if our string wouldn't be a standard date and time format for en-US
culture? Then we can specify our format with DateTime.TryParseExact
method. Let's look at which formats we can use to parsing our string.
1
matches with "M"
custom format specifier which is from 1
to 12
and single-digit month is formatted without a leading zero./
is a DateSeparator
and we can use it the same in our format because en-US
culture has /
as a DateSeparator
already. Remember, "/"
custom format specifier has a special meaning of replace me with current culture or supplied culture date separator22
matches with "dd"
custom format string which is from 01
to 31
and single-digit days is formatted with a leading zero. Remember, you can also use d format specifier in such a case but using wider formats is recommended.2004
matches with "yyyy"
custom format specifier which represents the year with a four digits.So, the right format will be M/dd/yyyy
in result.
string s = "1/22/2004";
DateTime dt;
if(DateTime.TryParseExact(s, "M/dd/yyyy", CultureInfo.GetCultureInfo("en-US"),
DateTimeStyles.None, out dt))
{
Console.WriteLine(dt); // 22 January 2004 00:00:00
}
Upvotes: 1
Reputation: 11844
You are referring to wrong format, so obviously it will throw exception. Below is what you are doing
string partialDate = "1/22";
string dtfi.DateSeparator = "/";
int _baseDate = 2004;
string ex = partialDate + dtfi.DateSeparator + _baseDate.ToString();
which gives you 1/22/2014 i.e., MM/dd/yyyy
and in code you are referring to
return DateTime.ParseExact(partialDate + dtfi.DateSeparator + _baseDate.ToString(), "dd/MM/yyyy", new CultureInfo("en-us");
Try using correct Format, to get the right result.
Upvotes: 0
Reputation: 48568
You should use format "m/dd/yyyy"
because datestring becomes 1/22/2004
return DateTime.ParseExact(partialDate + dtfi.DateSeparator + _baseDate.ToString(), "m/dd/yyyy", new CultureInfo("en-us"));
Upvotes: 2