开发者

Converting a string in ddMMyyyy format to a DateTime

开发者 https://www.devze.com 2023-01-17 03:27 出处:网络
How do I convert a string in ddMMyyyy format to a Dat开发者_Go百科eTime?Try using DateTime.ParseExact:

How do I convert a string in ddMMyyyy format to a Dat开发者_Go百科eTime?


Try using DateTime.ParseExact:

DateTime.ParseExact(yourDateString, "ddMMyyyy", CultureInfo.InvariantCulture);


See Parsing Date and Time and DateTime.ParseExact()

String dateString = "15072008";
String format = "ddMMyyyy";
try {
   DateTime result = DateTime.ParseExact(dateString, format, CultureInfo.InvariantCulture);
   Console.WriteLine("{0} converts to {1}.", dateString, result.ToString());
}
catch (FormatException) {
   Console.WriteLine("{0} is not in the correct format.", dateString);
}

Prints:

15072008 converts to 7/15/2008 12:00:00 AM.


You can do this very easily.

Here is example.

    String origionalDate = "12/20/2013"; // Format : MM/dd/yyyy
    string origionalFormat = "MM/dd/yyyy";
    string convertInToFormat="dd/MM/yyyy";
    String convertedDate;
    DateTime objDT;

    if (DateTime.TryParseExact(origionalDate, origionalFormat, CultureInfo.InvariantCulture, DateTimeStyles.None, out objDT) == true)
    {
        convertedDate = objDT.ToString(convertInToFormat);
        Response.Write("<b>Original DateTime Format ( " + origionalFormat + " ) : </b>" + origionalDate);
        Response.Write("<br/>");
        Response.Write("<b>Converted DateTime Format ( " + convertInToFormat + " )  : </b>" + convertedDate);
    }
    else
    {
        Response.Write("<b>Not able to parse datetime.</b>");
    }
0

精彩评论

暂无评论...
验证码 换一张
取 消