6

I have string of Date which can be in any format of date but I wanted to convert it to dd-MM-yyyy format.
I have tried every Convert.ToDatetime option which converts only to the System format. I want it to convert dd-MM-yyyy format.

Please reply. Thanks in Advance.

Keyur PATEL
  • 2,299
  • 1
  • 15
  • 41
RaviKPalanisamy
  • 87
  • 1
  • 2
  • 7

4 Answers4

18

Try this

DateTime dateTime = new DateTime();
dateTime = Convert.ToDateTime(DateTime.ParseExact("YouDateString", "dd-MM-yyyy", CultureInfo.InvariantCulture));

This will return DateTime with your Format

Shakir Ahamed
  • 1,290
  • 3
  • 16
  • 39
  • 2
    `Convert.ToDateTime` is not needed here as `DateTime.ParseExact` already return a DateTime object. – Boneless Aug 30 '17 at 13:02
4

Despite there being many answers and this being a duplicate answer, here are some possible solutions:

string formatted = date.ToString("dd-MM-yyyy");

or

string formatted = date.ToString("dd MM yyyy");

This link might help you with more formats and options.

Keyur PATEL
  • 2,299
  • 1
  • 15
  • 41
2

DateTime.ParseExact has an overloaded method to accepts multiple formats, include (all)possible formats you receive and parse the string. Once you get the valid DateTime you could apply desired format in converting to string.

  // ex...
  string dateString = ...;  // your date.

  string[] formats= {"M/d/yyyy h:mm:ss tt", "M/d/yyyy h:mm tt", 
                     "MM/dd/yyyy hh:mm:ss", "M/d/yyyy h:mm:ss", 
                     "M/d/yyyy hh:mm tt", "M/d/yyyy hh tt", 
                     "M/d/yyyy h:mm", "M/d/yyyy h:mm", 
                     "MM/dd/yyyy hh:mm", "M/dd/yyyy hh:mm",
                     "MM/d/yyyy HH:mm:ss.ffffff" };

   var date = DateTime.ParseExact(dateString, formats, new CultureInfo("en-US"), DateTimeStyles.None);

  //convert to desired format.
  var strDate = date.ToString("dd-MM-yyyy");
Hari Prasad
  • 16,716
  • 4
  • 21
  • 35
0

Here we go:

DateTime time = DateTime.Now;
Console.WriteLine(time.Day + "/" + time.Month + "/" + time.Year);

//return: 22/05/2016

Husni Salax
  • 1,968
  • 1
  • 19
  • 29