Solved

C# Date.ParseExact Question

Posted on 2014-11-25
23
180 Views
Last Modified: 2014-12-01
I am trying to convert a string to a date with an "am"/"pm" in it..  What I have created seems to work fine if the date/time is hardcoded in...

ftpDateTime = DateTime.ParseExact("1/25/14 06:33PM", "M/d/yy hh:mmtt", CultureInfo.InvariantCulture);

Open in new window


But NOT when the datetime is in a string field, even though the dates in both match exactly. I get a format error.. (see attached image showing date in the string field & error).

ftpDateTime = DateTime.ParseExact(dspDate, "M/d/yy hh:mmtt", CultureInfo.InvariantCulture);

Open in new window


Does anyone know WHY???     Thanks..

DateTimeParse Example
0
Comment
Question by:moosetracker
  • 7
  • 7
  • 4
  • +2
23 Comments
 
LVL 23

Expert Comment

by:Michael74
Comment Utility
You seem to be passing the control rather than its contents. Try passing dspDate.Text
0
 
LVL 1

Author Comment

by:moosetracker
Comment Utility
That would be nice, but not so easy..  The Date is not from an entry field, it is from Pulling a Directory list, and this is a simple string field after the string array from the Directory is separated to the dateTime, size and FileName.

           string ftpReport;
            string dspDate;
            DateTime ftpDateTime;
            int ftpDirLen;
            string ftpDteFormat;

:
:
            string[] detailDirectoryListing = ftpClient.directoryListDetailed("adorder/NewSPPush/Received");
            for (int i = 0; i < detailDirectoryListing.Length; i++) 
            {
                ftpDirLen = detailDirectoryListing[i].Length;
                if (ftpDirLen != 0)
                {
                    dspDate = detailDirectoryListing[i].Substring(1, 16);
                    dspDate = dspDate.Replace("-", "/");
                    ftpDateTime = DateTime.ParseExact("1/25/14 06:33PM", "M/d/yy hh:mmtt", CultureInfo.InvariantCulture);
                    ftpDateTime = DateTime.ParseExact(dspDate, "M/d/yy hh:mmtt", CultureInfo.InvariantCulture);
                   
                    //ftpDateTime = DateTime.Parse(dspDate);
                    ftpReport = detailDirectoryListing[i].Substring(39, ftpDirLen - 39);
                }
            }

Open in new window

0
 
LVL 23

Expert Comment

by:Michael74
Comment Utility
Something really weird going on here. Just guessing but try

dspDate = detailDirectoryListing[i].Substring(1, 16);
ftpDateTime = DateTime.ParseExact(dspDate, "M-d-yy hh:mmtt", CultureInfo.InvariantCulture);

Open in new window

and/or
ftpDateTime = DateTime.ParseExact(dspDate, "M/d/yy hh:mmtt", CultureInfo.InvariantCulture, AllowWhiteSpaces);

Open in new window


If these do not work I would place a watch on dspDate to confirm the full details on this variable since the error is suggesting the problem is in this string and that it does not match the date pattern "M/d/yy hh:mmtt"
0
 
LVL 10

Expert Comment

by:Walter Padrón
Comment Utility
I can't duplicate the error, for me works fine.

Guessing, check there is no others characters in the string and the spaces are really spaces and not tabs or anything else.

Best regards
0
 
LVL 21

Expert Comment

by:Tapan Pattanaik
Comment Utility
Hi moosetracker,

I hope the issue is within the below line of code.

dspDate = detailDirectoryListing[i].Substring(1, 16);

Open in new window


Please adjust the Substring parameter

Debug and check when array detailDirectoryListing  ="11/25/14 06:33PM" OR "1/25/14 06:33PM"

The value assign to variable  "dspDate" is in correct datetime format or not .

My suggestion is if  date stored in the array in "mm/DD/YY hh:mmtt" format then you will not face this type of  issue .

Note: 11/25/14 06:33PM is a 16 Character length.
           1/25/14 06:33PM  is a 15 Character length.
           Please check the parameter for  Substring(1, 16)
0
 
LVL 49

Accepted Solution

by:
Gustav Brock earned 250 total points
Comment Utility
How about using the more relaxed Parse:

DateTime.Parse(..)

/gustav
0
 
LVL 1

Author Comment

by:moosetracker
Comment Utility
Sorry I haven't addressed this until now.. I had time off for the holidays, and my house was without internet & cable for 3 days due to a snowstorm.. Just got it back..

Gustav - I did start out with the more relaxed parse, which didn't worked.. I had assumed it was the AM/Pm rather then military time (or something else the format from the ftp site did that caused it to complain)

Tapan - I will have to play with your idea.. I see what you are saying, If not an issue with this date, I see it might be an issue with some other date that is longer or shorter..  Problem is the date, filename, size & modify date all come in one line, so I will need to figure out how to pull the date out.. Perhaps I will need to figure out where in the line is the AM/PM, and then figure the length out from that.
0
 
LVL 23

Expert Comment

by:Michael74
Comment Utility
@moosetracker

Have a look at

DateTime.ParseExact(dspDate, "M/d/yy hh:mmtt", CultureInfo.InvariantCulture, AllowWhiteSpaces);

Open in new window


so that whitespaces do not break the parse.

The error you are getting is saying that the string you are trying to convert does not match the pattern you have specified and so I would strongly suggest that you place a watch on the variable dspDate and step through the code to ensure it is what you expecty
0
 
LVL 1

Author Comment

by:moosetracker
Comment Utility
I tried a few things:

First I allowed for the fact the date format will not always be 16 due to variation of month & day single/double digits.

            //string[] detailDirectoryListing = ftpClient.directoryListDetailed("app/pbs/spool/cm/normal");
            for (int i = 0; i < detailDirectoryListing.Length; i++) 
            {
                ftpDirLen = detailDirectoryListing[i].Length;
                if (ftpDirLen != 0)
                {
                    DateLen = detailDirectoryListing[i].Substring(1, 17).IndexOf("AM");
                    if (DateLen == -1)
                    {
                        DateLen = detailDirectoryListing[i].Substring(1, 17).IndexOf("PM");
                    }
                    DateLen = DateLen + 2;
                    dspDate = detailDirectoryListing[i].Substring(1, DateLen);
                    dspDate = dspDate.Replace("-", "/");
                    ftpDateTime = DateTime.ParseExact("1/25/14 06:33PM", "M/d/yy hh:mmtt", CultureInfo.InvariantCulture);
                    ftpDateTime = DateTime.ParseExact(dspDate, "M/d/yy hh:mmtt", CultureInfo.InvariantCulture);
                   
                    //ftpDateTime = DateTime.Parse(dspDate);
                    ftpReport = detailDirectoryListing[i].Substring(39, ftpDirLen - 39);
                }
            }
            /* Release Resources */
            ftpClient = null;

Open in new window


This didn't help.  Then I reformatted the space between date/time to be a ":"  so that we are sure what the field is..  Did not help.

date error
This drives me nuts.. As everything says it should work... But... I did get it to work... I used Gustav's suggestion (Although I did post that I already tried and it gave an error) perhaps some other adjustment got this to work (although not the added ":" I had to go back to a space between date/time)
0
 
LVL 23

Assisted Solution

by:Michael74
Michael74 earned 250 total points
Comment Utility
You are getting a Format Exception which according to Microsoft is the result of

s or format is an empty string.
-or-
s does not contain a date and time that corresponds to the pattern specified in format.
-or-
The hour component and the AM/PM designator in s do not agree.

http://msdn.microsoft.com/en-us/library/ms131038(v=vs.110).aspx

In your latest example the time is in 24 hour format. This corresponds to the format "HH" not "hh" which is 12 hour time and this will cause a Format Exception.
http://msdn.microsoft.com/en-us/library/8kb3ddd4(v=vs.110).aspx

Note: If you have a white space after the date in your original string then extract 16 characters and the AllowWhiteSpaces  option as this will cause the parse command to ignore leading, inner, and trailing white spaces not defined by format which would otherwise cause a formatexception to be thrown
0
Do You Know the 4 Main Threat Actor Types?

Do you know the main threat actor types? Most attackers fall into one of four categories, each with their own favored tactics, techniques, and procedures.

 
LVL 23

Expert Comment

by:Michael74
Comment Utility
So continuing from my last post use

dspDate = detailDirectoryListing[i].Substring(1, 16);
ftpDateTime = DateTime.ParseExact(dspDate, "M-d-yy HH:mmtt", CultureInfo.InvariantCulture, AllowWhiteSpaces);

Open in new window

0
 
LVL 10

Expert Comment

by:Walter Padrón
Comment Utility
@Michael74  The examples are not in 24 hours format.

@moosetracker What version of the Framework are you target in your project?
0
 
LVL 1

Author Comment

by:moosetracker
Comment Utility
Got it guys!!!  The space between the date/time was 2 spaces not 1 space...  I came back here and clicked on my photo of the dspdate after it was converted with the " " changed to ":" in order to try to see if it was indeed 24 hour military time now as suggested.. Didn't see the military time format, but I did notice what should have been a ":" between date/time was actually "::"  so I changed the coversion that a double space becomes the ":"  and now it is working !!!

Thanks for all the suggestions !!
0
 
LVL 49

Expert Comment

by:Gustav Brock
Comment Utility
You are welcome! Thanks for the feedback.

/gustav
0
 
LVL 23

Expert Comment

by:Michael74
Comment Utility
@moosetracker any reason why you never tried my repeated suggestions of
a. Carefully checking the datestring
b. Using AllowWhiteSpace
Not sure why you accepted a solution which did not work
0
 
LVL 1

Author Comment

by:moosetracker
Comment Utility
Actually the solution I accepted did work, just got rid of the .ParseExact and using the more generic .Parse..  I had tried that long before even trying the .ParseExact and it didn't work, which is what made me gravitate to the .ParseExact.. But, trying it again, it did work, don't know if the conversion of the date from "M-d-yy" to "M/d/yy" caused it to work, but it did work..

Looking at your latest post the "AllowWhiteSpace", was something I did not pick up on in your older posts..  I think it was because it was suggested after the statement that the last example was in military time.. I stopped reading and went off to check.. Then your message after just seemed to duplicate the code I had, because the "AllowWhiteSpace" addition was out of sight from the screen..

You are correct, it most definitely would have also fixed this issue with not realizing I had a double space, rather then a single space.. Sorry..  

I just gave it to Gustav because, at the time it seemed he came up with a solution, and then I found the solution to the .parseexact..  I wasn't going to give the credit to myself, so I gave it to him.   Sorry..
0
 
LVL 49

Expert Comment

by:Gustav Brock
Comment Utility
You can ask to have it changed. No problem here.

However, my initial thinking was that using ParseExact on strings that seemed not to be strict was at least a part of the issue.

/gustav
0
 
LVL 1

Author Comment

by:moosetracker
Comment Utility
Well, then I will look into having the moderators change it to a 50/50 split with both you guys sharing the credit..

Thanks Gustav for understanding. Yours definitely works, but besides getting my code to work (which was definitely important) I was looking for the answer to the .parseexact as it was new logic to me, and I wanted to understand it.. Understanding it, required getting it to work.
0
 
LVL 49

Expert Comment

by:Gustav Brock
Comment Utility
As I understand it, ParseExact is intended for "weird" strings not decodable by Parse, though of a fixed format - the classic being a tight string of numbers like 140111 where you can't read if it's year/month/day, day/month/year, or day/time, or time. Or where the values are part of a serial number or intermixed with non-relevant strings.

/gustav
0
 
LVL 23

Expert Comment

by:Michael74
Comment Utility
Hey guys, I was just feeling a bit unappreciated because I suggested the AllowWhiteSpace solution in message ID: 40472962. Moosetrackers kind response this morning resolved this and so I am happy with things as they stand. No need to change the points but thank you for the thought.

@Gustav you are correct. For anyone interested here is a good link
http://geekswithblogs.net/BlackRabbitCoder/archive/2012/01/05/c.net-little-wonders-the-datetime-tryparse-and-parseexact-methods.aspx
0
 
LVL 1

Author Closing Comment

by:moosetracker
Comment Utility
With Micheal74 - The last comment about the AllowWhiteSpace is a very good suggestion in order to get the .ParseExact to work.

Gustav - Was correct that this date did not need the .ParseExact, and that the more generic .Parse will work..

Thanks everyone for the help you offered.
0

Featured Post

Find Ransomware Secrets With All-Source Analysis

Ransomware has become a major concern for organizations; its prevalence has grown due to past successes achieved by threat actors. While each ransomware variant is different, we’ve seen some common tactics and trends used among the authors of the malware.

Join & Write a Comment

Many of us here at EE write code. Many of us write exceptional code; just as many of us write exception-prone code. As we all should know, exceptions are a mechanism for handling errors which are typically out of our control. From database errors, t…
Today I had a very interesting conundrum that had to get solved quickly. Needless to say, it wasn't resolved quickly because when we needed it we were very rushed, but as soon as the conference call was over and I took a step back I saw the correct …
In this tutorial you'll learn about bandwidth monitoring with flows and packet sniffing with our network monitoring solution PRTG Network Monitor (https://www.paessler.com/prtg). If you're interested in additional methods for monitoring bandwidt…
This demo shows you how to set up the containerized NetScaler CPX with NetScaler Management and Analytics System in a non-routable Mesos/Marathon environment for use with Micro-Services applications.

744 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

17 Experts available now in Live!

Get 1:1 Help Now