web-dev-qa-db-fra.com

Comment convertir la date du format aaaaMMdd au format mm-jj-aaaa

Je souhaite convertir une chaîne contenant la date au format yyyyMMdd en mm-dd-yyyy Format DateTime. Comment l'obtenir?

22
PramodChoudhari
var dateString = "20050802";
var date = myDate = DateTime.ParseExact(dateString,
                                    "yyyyMMdd",
                                    System.Globalization.CultureInfo.InvariantCulture);
46
Daniel Elliott
public static DateTime ConvertDate(string date, string pattern)
{
    DateTime retval = DateTime.MinValue;
    if (System.DateTime.TryParseExact(date, pattern, System.Globalization.CultureInfo.InvariantCulture, DateTimeStyles.None, out retval))
       return retval;

    // Could not convert date..
    return DateTime.MinValue;
}


DateTime myDate = ConvertDate("20101230", "yyyyMMdd");
3
stian.net
CultureInfo provider = CultureInfo.CreateSpecificCulture("en-UK");   

string dateString = "19850121"; //in yyyyMMdd format 

string oldFormat = "yyyyMMdd"; 

DateTime result = DateTime.ParseExact(dateString, oldFormat, provider); //MM/dd/yyyyformat 
1
PramodChoudhari