20

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)
leppie
  • 115,091
  • 17
  • 196
  • 297
Refael
  • 6,753
  • 9
  • 35
  • 54

5 Answers5

24

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.

Fredrik Mörk
  • 155,851
  • 29
  • 291
  • 343
15

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
MarcinJuraszek
  • 124,003
  • 15
  • 196
  • 263
2

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).

Jhonny D. Cano -Leftware-
  • 17,663
  • 14
  • 81
  • 103
D Stanley
  • 149,601
  • 11
  • 178
  • 240
1

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)
Community
  • 1
  • 1
Michael Freidgeim
  • 26,542
  • 16
  • 152
  • 170
0

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.

jomsk1e
  • 3,585
  • 7
  • 34
  • 59