简体   繁体   中英

Convert.ToDateTime('Datestring') to required dd-MM-yyyy format of date

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.

Try this

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

This will return DateTime with your Format

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.

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");

Here we go:

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

//return: 22/05/2016

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM