Datetime conversion and parsing

15,449

Solution 1

I just rewrite the format string and it resolves the issue. Found that rewriting { } braces resolved it. Please try it.

Solution 2

try doing this like

DateTime ckDate = new DateTime(2012, 09, 24);

more can be found here http://www.dotnetperls.com/datetime

you can also convert to string to datetome but you have to check ahead of time the the string is date

 DateTime ckDate =Convert.DateTime(yourinputstring);

you can also use parse

DateTime ckDate=DateTime.Parse(yourinputstring);

Solution 3

You have 15 format specifier in your format string, but only 14 parameters. Unless I have missed one, your format string is invalid.

/*
username={0}& ->username, 
password={1‌​}& -> password, 
intResortID={2}& -> intresortid, 
strpartysurname={3}& -> strPartySurname, 
strpartyfirstname={4}& ->strPartyFirstName, 
strpartyprefix={5}& -> intQuantityTotal, 
intQuantityTotal={6}& -> ckDate, 
dtmLine1={7}& -> BBRoom, 
strRoomType1={8}& -> RoomQty, 
intRooms1={9}& -> NoofNights, 
intnights1={10}& -> flightNO, 
strFlightNo&{11}& -> strNotes, 
strNotes{12}& -> ResBookingID, 
strBookingCode{13}& -> PromotionCode
strPromotionCode={14}", -> ????? Missing ????
);                                    
*/

As far as date it concerned, you haven't shown how you got ckDate, if it's a string with date in it, or is it a DateTime. Also, from parameter list, looks like ckDate is mapped to something that is called "intQuantityTotal".

If ckDate is a string, then use DateTime.TryPrase method to convert it actual DateTime.

If you are converting from string follow this, assuming your input date is in a string variable called "inputDate":

DateTime checkInDate;
if (!DateTime.TryParse(inputDate, out checkInDate))
{
 //This is error condition, which means your string date wasn't convertible to DateTime
}
else
{
   // Variable checkInDate now contains converted DateTime.
   // You can put your format string here and your DateTime should work fine.
}

Solution 4

Try using DateTime.ParseExact Method

DateTime result = DateTime.ParseExact("2012-09-24", "yyyy-MM-dd", System.Globalization.CultureInfo.InvariantCulture);

Solution 5

I advise you to use DateTimes constructor when possible, and not bother with converting strings to dates.

DateTime t = new DateTime(2012, 9, 24);

If you still want to start from a string, you need to use variations of DateTime.Parse

The simplest thing would work:

DateTime t = DateTime.Parse("2012-9-24");

in order to explicitly specify the format of the date use DateTime.ParseExact

Since you mentioned that the date string is entered by the user, I would assume you want a feedback loop in case the user enters an malformed date. In this case you should use DateTime.TryParse

Share:
15,449
user1270384
Author by

user1270384

programmer

Updated on June 09, 2022

Comments

  • user1270384
    user1270384 almost 2 years

    My code gives the following error: Input string was not in a correct format.

    with this hint:

    When converting a string to DateTime, parse the string to take the date before putting each variable into the DateTime object

    Below is my code: (Edited to only show problematic code)

     string username ="aits";
     string password = "12345";
     Int32 intresortid=7;
     string strPartySurname = "Kumar"; ;
     string strPartyFirstName = "Test";
     string strPartyPrefix = "Mr & Mrs";
     Int16 intQtyAdults=1;
     Int16 intQtyTotal=1;
     string PromotionCode = "TIF";
     string flightNO = "FlighDJ76";
     string strNotes = "<nl>Provide Breakfast<nl>Honeymooners";
    
     try
        {
    
            string url = string.Format("http://localhost/insHold.asp?username={0}&password={1‌​}&intresortid={2}&strPartySurname={3}&strPartyFirstName={4}&strPartyPrefix={5}&intQtyAdults={6}&intQtyTotal={7}&dtmLine1={8:yyyy-MM-dd}&strRoomType1={9}&intRooms1={10}&intnights1={11}&strFlightNo={12}&strNotes={13}&strBookingCode={14}&strPromotionCode={15}", username, password, intresortid, strPartySurname, strPartyFirstName, strPartyPrefix, intQtyAdults, intQtyTotal, CheckInDate, BBRoom, RoomQty, NoofNights, flightNO, strNotes, ResBookingID, PromotionCode);                                                                                                                                                                                                                                                        
            WebRequest request = HttpWebRequest.Create(url);
            WebResponse response = request.GetResponse();
            StreamReader reader = new StreamReader(response.GetResponseStream());
            string urlText = reader.ReadToEnd();
            bookid = Convert.ToInt16(urlText);
        }
        catch (System.ApplicationException ex)
        {
            throw ex;
        }
    

    I don't know how to correct this as my DateTime value: CheckInDate is already of type date.

    Can somebody please tell me how to fix this or point me in the right direction.

    • lc.
      lc. over 11 years
      That won't compile. Missing some quotes or a new DateTime()?
    • user1270384
      user1270384 over 11 years
      Please see edited CheckInDate
    • user1270384
      user1270384 over 11 years
      I don't get you..What do you mean?
  • user1270384
    user1270384 over 11 years
    No can't do that because my ckdate is user entered so it will always change based on what user enters. Do you have something for that scenario?
  • user1270384
    user1270384 over 11 years
    The date "2012-09-24" is actually an example. As the value for the variable in its place is user entered. Do you have a solution for that.
  • user1270384
    user1270384 over 11 years
    my code would become something like this: DateTime.ParseExact(CheckInDate, "yyyy-MM-dd", CultureInfo.InvariantCulture); but gives an error of too many arguments
  • John Woo
    John Woo over 11 years
    as you can see yyyy-MM-dd is the format of the values being entered. so for example you have entered JAN-01-2012 the format should be MMM-dd-yyyy
  • John Woo
    John Woo over 11 years
    @user1270384 you need to add the namespace of the culture: System.Globalization.CultureInfo.InvariantCulture
  • John Woo
    John Woo over 11 years
    @user1270384 did you see the screenshot? it worked on my machine. i.imgur.com/bSzlG.png
  • user1270384
    user1270384 over 11 years
    Yes it will not compile, it gives the above mentioned error thats why I posted the question and it can't be string CheckInDate because the CheckIndate value comes from a web service which will only accept the format as Datetime.
  • user1270384
    user1270384 over 11 years
    thank you looking through the screen shot right now, let me paste me code so we can see where I went wrong. i get the following error:Error 7 A using namespace directive can only be applied to namespaces; 'System.Globalization.CultureInfo' is a type not a namespace
  • Vitaliy
    Vitaliy over 11 years
    @user1270384, I have completely lost track of what you re trying to do.. please post the entire problematic code sample, but only the problematic part. In the above sample, there is a lot of noise.
  • user1270384
    user1270384 over 11 years
    Amended to show where problem is. Inside the string url = portion
  • Vitaliy
    Vitaliy over 11 years
    Better now but still very noisy. Which on of the statements throws the exception?
  • user1270384
    user1270384 over 11 years
    Please read comment above your own. string url =. Error points at variable received for CheckInDate for Parameter dtmLine1
  • user1270384
    user1270384 over 11 years
    Hi @samy Which part and how? Please provide example using string url above, if that is what you are speaking of
  • Vitaliy
    Vitaliy over 11 years
    OK. You are saying that the error is thrown in "string url =", there is absolutely no need in the code shown below. What we need is the statement that throws the exception, and the parameter values you are passing to it. In order to further narrow down the problem, I would start by building the string step by step. First only with {0} than with {0} and {1}.. at some point you get the exception say for parameter {7}. Than you try it only with this one (as {0}) and you get the most exact reproduction of the problem.
  • user1270384
    user1270384 over 11 years
    I had the parameter values earlier you complained it was too noisy for you..you're really just not helping right now!
  • user1270384
    user1270384 over 11 years
    Sorry that must have been happened when I cleaned up the code when a user complained it was too noisy. I have amended with the missing values. It all matches but the error still comes. Please have a look and advise
  • user1270384
    user1270384 over 11 years
    Thank for that I have matched all the values and also formatted the dtmline1 value to the way you have explained above but the error still comes. Hoping for your insight
  • Vitaliy
    Vitaliy over 11 years
    Well, it is part of understanding the problem. I said that it seems you have a lot of unnecessary code. I, however, do not know what is the problematic code and what is not. so I asked you to clean things up a little. You chose what to remove and what to keep. A big part of getting an answer to your question (not just in SO) is knowing how to frame it, how to give the necessary data and nothing more.
  • loopedcode
    loopedcode over 11 years
    Your format string for CheckInDate is set as dtmLine1={8:yyyy-MM-dd}. This format specifier is only valid for a DateTime data type. What is the actual data type of CheckInDate? You haven't shown that part of the code. Is CheckInDate DateTime object or is it a string? My guess is, it is a string and you are trying to apply a DateTime format string to.
  • user1270384
    user1270384 over 11 years
    Its supposed to be of type Datetime but it still gives an error, even if I take it as a string and then convert it to datetime before calling it in the dtmLine1 parameter I get the same error. CheckInDate is entered by the user
  • loopedcode
    loopedcode over 11 years
    Check bottom of my edited post. I added code which can verify if your string is parse-able.