Вопрос

How to convert any date format to a specified format in C#.

For example:

If Date Format is

14.11.2011 or 14/11/2011 

Looking for a conversion function which converts into

yyyy-MM-dd format like 2011-11-14
Это было полезно?

Решение

Easy peasy:

var date = DateTime.Parse("14/11/2011"); // may need some Culture help here
Console.Write(date.ToString("yyyy-MM-dd"));

Другие советы

Take a look at DateTime.ToString() method, Custom Date and Time Format Strings and Standard Date and Time Format Strings

string customFormattedDateTimeString = DateTime.Now.ToString("yyyy-MM-dd");

You can use the DateTime.Parse or DateTime.ParseExact methods to parse the string into a DateTime then you can use the DateTime.ToString() to return the date in the new format. For standard formatting check this page for custom date formats this

string s = "May 29,2012";
DateTime dt;
DateTime.TryParse(s, out dt);

Response.Write(dt.ToString("MM/dd/yyyy"));
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top