How about this:
string test = "01-12-12";
try{
DateTime dateTime = DateTime.Parse(test);
test = dateTime.ToString("dd/yyyy");
}
catch (FormatException exc)
{
MessageBox.Show(exc.Message);
}
Where test will be equal to "12/2012"
Hope it helps!
Please read HERE.
You can use Convert.ToDateTime is it is shown at How to convert a Datetime string to a current culture datetime string
DateTimeFormatInfo usDtfi = new CultureInfo("en-US", false).DateTimeFormat;
var result = Convert.ToDateTime("12/01/2011", usDtfi)
If value
is a string
in that format and you'd like to convert it into a DateTime
object, you can use DateTime.ParseExact
static method:
DateTime.ParseExact(value, format, CultureInfo.CurrentCulture);
Example:
string value = "12/12";
var myDate = DateTime.ParseExact(value, "MM/yy", System.Globalization.CultureInfo.InvariantCulture, System.Globalization.DateTimeStyles.None);
Console.WriteLine(myDate.ToShortDateString());
Result:
2012-12-01
DateTime
doesn't have a format. the format only applies when you're turning a DateTime
into a string, which happens implicitly you show the value on a form, web page, etc.
Look at where you're displaying the DateTime and set the format there (or amend your question if you need additional guidance).
Source: Stackoverflow.com