Praveen Kumar Ch
Praveen Kumar Ch

Reputation: 9

unable to convert string to date in asp.net correctly

I unable to convert string to date, my string like 17/12/2012 Code written for this is shown below

public string Date_Convert(string dt1)
{
    string strdate = string.Empty;
    Thread.CurrentThread.CurrentCulture = new CultureInfo("en-GB");
    DateTime dt = Convert.ToDateTime(dt1);
    strdate = dt.Month.ToString() + "/" + dt.Day.ToString() + "/" + dt.Year.ToString();
    Thread.CurrentThread.CurrentCulture = new CultureInfo("en-US");
    return strdate;
}

It is working fine in my local system. And not working in my server(which is located at Australia)of course I tried with different culture settings in the above code,

I'm using this date string in sql query in where condition.

please help me, It killed my one day time, and thanks in advance.

Upvotes: 0

Views: 2115

Answers (3)

Thorsten Dittmar
Thorsten Dittmar

Reputation: 56697

Instead of switching the culture, why don't you do something like this:

public string Date_Convert(string dt1)
{
    DateTime dt = DateTime.ParseExact(dt1, "dd/MM/yyyy", new CultureInfo("en-GB"));
    return dt.ToString("d", new CultureInfo("en-US"));
}

Also: If you use the value in an SQL query (and provided that your query works on a DATETIME field, not NVARCHAR), you should also consider using a parameterized query to pass the DateTime value to the database to avoid SQL injection.

For example:

DateTime value = DateTime.Parse(dt1, new CultureInfo("en-GB"));
using (SqlCommand cmd = new SqlCommand("SELECT ... FROM ... WHERE Date = @date", connection))
{
    cmd.Parameters.AddWithValue("@date", value);
    ...
}

Upvotes: 2

andy
andy

Reputation: 6079

The format of the DataTime will depend on the current culture of your application. Inorder to have a specific format throught your application you can set the tag in the web.config file under section. In such case you need not write code to convert the datatime to proper format. By default all the dates will be set to the format specified.

http://forums.asp.net/t/1109183.aspx/1

More Info

Upvotes: 0

dutzu
dutzu

Reputation: 3910

Try DateTime.ParseExact() it receives as parameter the pattern so for your case it would be "dd/MM/yyyy"

Upvotes: 1

Related Questions