Convert Date Formatting Codes to date

你离开我真会死。 提交于 2019-12-05 15:18:29

My go-tos for DateTime Input and Output:

http://www.dotnetperls.com/datetime-parse for input (parsing)

http://www.csharp-examples.net/string-format-datetime/ for output (formatting)

string dateString = "01 01 1992";
string format = "MM dd yyyy";

DateTime dateTime = DateTime.ParseExact(dateString, format, CultureInfo.InvariantCulture);

Edit since his edit makes my above answer irrelevant (but will leave there for reference):

From what you're saying, you want to output today's date in a dynamically-defined format?

So if I want to see month, date, year, I say "MM dd YY" and you return it to me?

If so:

DateTime dt = DateTime.Today; // or initialize it as before, with the parsing (but just a regular DateTime dt = DateTime.Parse() or something quite similar)

Then

String formatString = "MM dd YY";
String.Format("{0:"+ formatString+"}", dt);

Your question is still quite unclear, though.

You can use DateTime.TryParseExact to parse a string to date and DateTime-ToString to convert it back to string with your desired format:

DateTime parsedDate;
if (DateTime.TryParseExact("11 11 2013", "MM dd yyyy", System.Globalization.CultureInfo.InvariantCulture, System.Globalization.DateTimeStyles.None, out parsedDate))
{ 
    // parsed successfully, parsedDate is initialized
    string result = parsedDate.ToString("MM dd yyyy", System.Globalization.CultureInfo.InvariantCulture);
    Console.Write(result);
}

Use ParseExact:

var date = DateTime.ParseExact("9 1 2009", "M d yyyy", CultureInfo.InvariantCulture);
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!