I use convert like:
Convert.ToDateTime(value)
but i need convert date to format like "mm/yy".
I'm looking for something like this:
var format = "mm/yy";
Convert.ToDateTime(value, format)
I use convert like:
Convert.ToDateTime(value)
but i need convert date to format like "mm/yy".
I'm looking for something like this:
var format = "mm/yy";
Convert.ToDateTime(value, format)
You should probably use either DateTime.ParseExact
or DateTime.TryParseExact
instead. They allow you to specify specific formats. I personally prefer the Try
-versions since I think they produce nicer code for the error cases.
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).
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)