Link to home
Start Free TrialLog in
Avatar of Ammar Iqbal
Ammar IqbalFlag for Norway

asked on

Parsing strings into DateTime object in C#

In the attached code script , from date is being working perfectly fine, but on parsing todate, it is saying that The DateTime represented by the string is not supported in calendar System.Globalization.GregorianCalendar.

The syntax and format for both the dates are exactly the same ,Its giving me quite a bad headache.

Urgently required
string fromdate = txtFromdate.Text.ToString();
            string todate = txtToDate.Text.ToString();
            if(fromdate != "")
            {
                fromdate = DateTime.ParseExact(txtFromdate.Text.ToString(), "dd.MM.yyyy hh:mm:ss", null).ToString("MM/dd/yyyy hh:mm:ss");
            }
            
            if (todate != "")
            {
               todate = DateTime.ParseExact(txtToDate.Text.ToString(), "dd.MM.yyyy hh:mm:ss", null).ToString("MM/dd/yyyy hh:mm:ss");
               
            }
            else if (todate == "")
            {
                DateTime current = DateTime.Now;
                todate = current.ToString();
            }

Open in new window

Avatar of Avodah
Avodah
Flag of United Kingdom of Great Britain and Northern Ireland image

What dates are you passing to this routine. Could you post the exact string so that the issue could be replicated.

DaTribe
Are you sure the input is in the correct format?

Passing in a date "12.13.2010 12:12:12" will throw that error -- the month and day are transposed.
Avatar of Ammar Iqbal

ASKER



 From date  is this "11/10/2010 11:04:40" which is perfectly fine
Todate is this  "11.24.2010 08:10:20".. it  is giving this exception

I have given the parsed result of fromdate, and todate is unsuccessfull in parsing
i am going nuts
ASKER CERTIFIED SOLUTION
Avatar of Avodah
Avodah
Flag of United Kingdom of Great Britain and Northern Ireland image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
i want to have this pattern of time with "/" in it , because i need to parse in the filter criteria for the sql query, and the datetime fields of sql query recognize "/" slashes
ok
Got it.. It was  fool of me , that i set the format of todate as MM.dd, and iam trying over here as dd.mm

thankx  for looking into it
Simply replace the . with /
Avatar of kris_per
kris_per


Try changing  dd.MM.yyyy to =>  MM.dd.yyyy like:
...
if(fromdate != "")
            {
                fromdate = DateTime.ParseExact(txtFromdate.Text.ToString(), "MM.dd.yyyy hh:mm:ss", null).ToString("MM/dd/yyyy hh:mm:ss");
            }
            
            if (todate != "")
            {
               todate = DateTime.ParseExact(txtToDate.Text.ToString(), "MM.dd.yyyy hh:mm:ss", null).ToString("MM/dd/yyyy hh:mm:ss");
               
            }
...

Open in new window