Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Error while converting string to DateTime after publishing to web server

Tags:

c#

datetime

I am using below code

    DateTime dtt=new DateTime();
    dtt = Convert.ToDateTime(FromDate);


  //  DateTime dtt = DateTime.Parse(FromDate); //this also gives the same error

    con = new MySqlConnection(conString);
    con.Open();
    for (int i = 1; i <= TotalDays; i++)
    {         
        string updateHotelBooking = "Update tbl_hotelbookingdetail set `BookedRoom`=`BookedRoom`+"+1+", `AvailableRoom`=`TotalRoom`-`BookedRoom` where `HotelID`="+HotelID+" AND `CurrentDate`='"+dtt.ToString("dd-MM-yyyy")+"'";
        MySqlCommand cmd7=new MySqlCommand(updateHotelBooking,con);
        cmd7.ExecuteNonQuery();                
        dtt = dtt.AddDays(1);
    }

This code is in one of my webservice which I am using for iPhone application.

here FromDate is string with value in this formate 15-11-2011 which is coming from the application in string format. I am converting it to DateTime because in loop of total days I need to add day to dtt.

It is working fine on local host with dtt value 15-11-2011 00:00:00

but when I published it,it gives error

String was not recognize as valid DateTime

like image 290
Ankit Chauhan Avatar asked Aug 08 '26 13:08

Ankit Chauhan


1 Answers

This is almost certainly because your server uses a different culture by default - and your code is just using the current thread culture.

You can specify this using DateTime.Parse - or specify the pattern explicitly with DateTime.ParseExact or DateTime.TryParseExact - but we need to know more about where the string is coming from to suggest the best approach. Is it from the user? If so, you should use the user's culture to parse it. Is it a specific format (e.g. from an XML document) instead? If so, parse using that specific format.

Ideally, get rid of the string part entirely - if you're fetching it from a database for example, can you store it and fetch it as a DateTime instead of as a string? It's worth trying to reduce the number of string conversions involved as far as possible.

EDIT: To parse from a fixed format of dd-MM-yyyy I would use:

DateTime value;
if (DateTime.TryParseExact(text, "dd-MM-yyyy",
                           CultureInfo.InvariantCulture,
                           DateTimeStyles.AssumeUniversal,
                           out value))
{
     // Value will now be midnight UTC on the given date
}
else
{
    // Parsing failed - invalid data
}
like image 96
Jon Skeet Avatar answered Aug 10 '26 10:08

Jon Skeet