-1

Converting a String to DateTime

As the above link says I can do conversion if I'm having a the complete dd/mm/yyyy,But I'm having only dd/mm not the year field.

I have achieve it by changing the date to mm/dd format and using Convert.ToDateTime(date).So any help please.

Community
  • 1
  • 1
Sribin
  • 307
  • 4
  • 16

3 Answers3

2

You can parse that string. Just remember that the Month part is MM not mm (minutes)

string data = "01/01";
DateTime dt;
DateTime.TryParseExact(data, "dd/MM", CultureInfo.CurrentCulture, DateTimeStyles.None, out dt);
Console.WriteLine(dt.ToLongDateString());

Of course the missing year is assumed to be the current year

Steve
  • 213,761
  • 22
  • 232
  • 286
0

You can use this source to learn more about specifiers for parsing custom date's.

Put your string variable instead of CustomDate field.

DateTime d = DateTime.ParseExact(CustomDate, "dd/MM",System.Globalization.CultureInfo.CurrentCulture);
Berkays
  • 364
  • 3
  • 10
0

I would use the function DateTime.TryParseExact since you can use it within an If - else structure very easily

private DateTime date;
private myString = "23/04";

if (DateTime.TryParseExact(myString, "dd/MM", CultureInfo.InvariantCulture, DateTimeStyles.None, out date))
{
    myDate = date;
}
else
{
    //do nothing
}

With this you can catch errors when parsing the string.

Christoph
  • 323
  • 4
  • 16