Reputation: 327
So I had to convert a date in the format of (MM-dd-yyyy) to (dd-MMM-yyyy). What I ended up doing was this...
string strProvisionalDate = "04-22-2001";
string strFormat = "MM-dd-yyyy";
DateTime dtProvisional;
DateTime.TryParseExact(strProvisionalDate, strFormat, CultureInfo.InvariantCulture, DateTimeStyles.None, out dtProvisional);
string strProvisionalDateConverted = dtProvisional.ToString("dd-MMM-yyyy");
string strFormatConverted = "dd-MMM-yyyy";
DateTime dtProvisionalConverted;
DateTime.TryParseExact(strProvisionalDateConverted, strFormatConverted, CultureInfo.InvariantCulture, DateTimeStyles.None, out dtProvisionalConverted);
Basically, I converted it to DateTime, converted that to a string in the format I wanted, then converted that back to DateTime. It works, but I was curious to ask if there was a better way to do this...it doesn't seem very elegant.
edit: Turns out, in this dtProvisional and dtProvisionalConverted end up being the same. So my new question would be, how can I convert a string in the format of MM-dd-YYYY to a DateTime in the format of dd-MMM-yyyy? dtProvisional is going into a SQL database, and it has to be in Date format.
Upvotes: 3
Views: 5406
Reputation: 1
was searching details on similar line.... that worked for me....
DateTime IncentiveDate;
/// <summary>
/// Input Format: ddMMyy eg. 070711
/// Output Format: dd-MMM-YYYY eg. 07-JUL-2011
/// </summary>
public string IncentiveDateAsString
{
set
{
DateTime.TryParseExact(value, "ddMMyy", CultureInfo.InvariantCulture, DateTimeStyles.None, out IncentiveDate);
}
get
{
return IncentiveDate.ToString("dd-MMM-yyyy");
}
}
Upvotes: 0
Reputation: 750
The DateTime object doesn't store date/time as a format, it stores it as a number of ticks since the epoch. There should be no difference between dtProvisional and dtProvisionalConverted DateTime as object (their undelying value should be the same). The string format can always be changed when outputting the DateTime to a string using the String Format functionality.
See the remarks section on this MSDN article.
I this will format your date correctly for outputting:
String.Format("{0:dd-MMM-yyyy}", dt);
Upvotes: 6