Click here to Skip to main content
15,880,796 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I have Date in any format in a string variable .
I want to format/ convert in given format.
I have written following line....

ConvertedValue = Convert.ToDateTime(CValue.Trim()).ToString(StrWizFormat.Trim());

OR

ConvertedValue = ConvertFieldDatetimeFormat(CValue.Trim(), StrWizFormat.Trim()).ToString(StrWizFormat.Trim());

private static DateTime ConvertFieldDatetimeFormat(string DValue, string DFormat)
    {
        System.Globalization.DateTimeFormatInfo dateInfo = new System.Globalization.DateTimeFormatInfo();
        dateInfo.ShortDatePattern = DFormat;
        DateTime CnvDtValue;

        if (DValue.Trim() != string.Empty)
        {
            CnvDtValue = Convert.ToDateTime(DValue.Trim(), dateInfo);
        }
        else
        {
            CnvDtValue = new DateTime();
        }
        return CnvDtValue;
    }

but I am getting error in some case ....
Please modify my function ....
or suggest me, if you have best trick ....


With Regards
Manoj
Posted
Updated 19-Jan-12 22:22pm
v2

If you have a specific format to to convert, use TryParseExact:
C#
DateTime dt;
string date = "31/12/2011";
if (DateTime.TryParseExact(date, "dd/MM/yyyy", CultureInfo.InvariantCulture, DateTimeStyles.None, out dt))
    {
    }
 
Share this answer
 
Comments
Manoj Kumar Choubey 23-Jan-12 0:09am    
Thank you Dear I will try your solution ....
I want to ask a Question, what is your good name please ?
OriginalGriff 23-Jan-12 4:07am    
OriginalGriff or Griff is fine!
 
Share this answer
 
 
Share this answer
 
v3

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900