Click here to Skip to main content
15,881,173 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi All,

I want to convert a string to datetime.
the string is '17/03/2001'. this is in 'dd/MM/yyyy' format.
my system datetime format is 'MM/dd/yyyy' format
I tried converting like
C#
Convert.ToDateTime("17/03/2001")
. Now it catches error.

But when I change my system date format to 'dd/MM/yyyy' conversion works fine.

I need to convert date to a specific format irrespective of system date. Since I am working in a web application.

any one please help me.
Posted
Comments
[no name] 13-Mar-15 4:43am    
You can convert simply use CultureInfo.InvariantCulture.check my solution.

C#
DateTime.ParseExact("17/03/2001", "dd/MM/yyyy", CultureInfo.InvariantCulture);
 
Share this answer
 
v2
Comments
CHill60 13-Mar-15 4:44am    
Beat me to it!
Here's the link to the MSDN Documentation[^] for it
C#
using System.Globalization;

txtDate.Text = "17/03/2001";
DateTime From = DateTime.ParseExact(txtDate.Text, "dd/MM/yyyy", CultureInfo.InvariantCulture);


Ref : CultureInfo.InvariantCulture Property
 
Share this answer
 
Use A Custom Class for DateTime related work

C#
public static class Timechanger{
    public static DateTime StringToDate(string strDt, char[] separator)
    {
        string[] dateparts1 = strDt.Split(separator);
        var sdate = new DateTime(Convert.ToInt32(dateparts1[2]), Convert.ToInt32(dateparts1[1]),
            Convert.ToInt32(dateparts1[0]));
        return sdate;
    }

    public static DateTime StringToDate(string strDt)
    {
        return StringToDate(strDt, new[] {'-', '/'});
    }

    public static string DateToString(DateTime dt)
    {
        string strDt = Convert.ToString(dt.Day) + "/" + Convert.ToString(dt.Month) + "/" + Convert.ToString(dt.Year);
        return strDt;
    }
    }
 
Share this answer
 

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