Solved

C# Date.ParseExact Question

Posted on 2014-11-25
23
219 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 7
  • 7
  • 4
  • +2
23 Comments
 
LVL 23

Expert Comment

by:Michael Fowler
ID: 40466015
You seem to be passing the control rather than its contents. Try passing dspDate.Text
0
 
LVL 1

Author Comment

by:moosetracker
ID: 40466028
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:Michael Fowler
ID: 40466069
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
Use Filtering Commands to Process Files in Linux

Learn how to manipulate data with the help of various filtering commands such as `cat`, `fmt`, `pr`, and others in Linux.

 
LVL 10

Expert Comment

by:Walter Padrón
ID: 40467941
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
ID: 40468526
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 51

Accepted Solution

by:
Gustav Brock earned 250 total points
ID: 40468698
How about using the more relaxed Parse:

DateTime.Parse(..)

/gustav
0
 
LVL 1

Author Comment

by:moosetracker
ID: 40472953
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:Michael Fowler
ID: 40472962
@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
ID: 40472984
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:Michael Fowler
Michael Fowler earned 250 total points
ID: 40473001
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
 
LVL 23

Expert Comment

by:Michael Fowler
ID: 40473003
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
ID: 40473925
@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
ID: 40474005
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 51

Expert Comment

by:Gustav Brock
ID: 40474022
You are welcome! Thanks for the feedback.

/gustav
0
 
LVL 23

Expert Comment

by:Michael Fowler
ID: 40474475
@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
ID: 40474623
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 51

Expert Comment

by:Gustav Brock
ID: 40474812
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
ID: 40474848
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 51

Expert Comment

by:Gustav Brock
ID: 40474871
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:Michael Fowler
ID: 40474898
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
ID: 40474949
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

Windows Server 2016: All you need to know

Learn about Hyper-V features that increase functionality and usability of Microsoft Windows Server 2016. Also, throughout this eBook, you’ll find some basic PowerShell examples that will help you leverage the scripts in your environments!

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

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…
A long time ago (May 2011), I have written an article showing you how to create a DLL using Visual Studio 2005 to be hosted in SQL Server 2005. That was valid at that time and it is still valid if you are still using these versions. You can still re…
There's a multitude of different network monitoring solutions out there, and you're probably wondering what makes NetCrunch so special. It's completely agentless, but does let you create an agent, if you desire. It offers powerful scalability …
Michael from AdRem Software explains how to view the most utilized and worst performing nodes in your network, by accessing the Top Charts view in NetCrunch network monitor (https://www.adremsoft.com/). Top Charts is a view in which you can set seve…

617 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