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)
ToDateTime('Datestring') to required dd-MM-yyyy format of date.
string strDate = DateTime. Now. ToString("MM/dd/yyyy");
You can use DateTime. TryParse() : which will convert the specified string representation of a date and time to its DateTime equivalent and returns a value that indicates whether the conversion succeeded.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With