Click here to Skip to main content
15,908,674 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I am getting this Error on the webserver suppose if i put the date as 30/12/2012, but it is working in my local machine.

if (row["Approve_Date"] != DBNull.Value)
    DateTime aprRecDate = (DateTime)row["Approve_Date"];
    if (aprRecDate.ToString("dd/MM/yyyy") != "01/01/1900")
        txtAprvDate.Text = aprRecDate.ToString("dd/MM/yyyy");

Use DateTime.ParseExact[^].
DateTime date = DateTime.ParseExact(this.Text, "dd/MM/yyyy", null);
Share this answer
Robymon 8-Jun-12 6:36am    
I tried this also, but still showing the same error
The reason is that by default the DateTimeFormat of the CurrentCulture is used in parsing the date.

In your local machine the DateTimeFormat of the CurrentCulture may be in the dd/MM/yyyy format hence there may not be error.

Whereas on the webserver the DateTimeFormat of the CurrentCulture may be MM/dd/yyyy and since 30 is more than maximum month value the above error may be thrown.

So, when using DateTime.ParseExact the InvariantCulture can be used to avoid this problem as shown below:
DateTime date = DateTime.ParseExact("30/12/2012","d/M/yyyy",

The d/M/yyyy format matches the date and month both in single digit and double digit like 09/05/2012 and 9/5/2012 whereas the dd/MM/yyyy format requires both the date and month to be in exactly two digits. Otherwise it will throw error. So, 09/05/2012 can be read by it, but for 9/5/2012 it will throw error.

Hence, it is preferable to use d/M/yyyy format.
Share this answer
Maciej Los 8-Jun-12 10:31am    
Good explanations, my 5!
VJ Reddy 9-Jun-12 0:43am    
Thank you, losmac :)
Shahin Khorshidnia 9-Jun-12 2:59am    
Yes losmac. my five too
VJ Reddy 9-Jun-12 3:05am    
Thank you, Shahin :)

Share this answer
Maciej Los 8-Jun-12 10:59am    
Bad answer. Try to convert string "9-5-2012" to date. Read about Convert.ToDateTime(objDateTime) - Remarks section.
If you prefer not to handle an exception if the conversion fails, you can call the DateTime.TryParse method instead. It returns a Boolean value that indicates whether the conversion succeeded or failed.

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