10 Replies - 1268 Views - Last Post: 24 March 2019 - 05:29 PM Rate Topic: -----

#1 juniordev101   User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 10
  • Joined: 22-March 19

Parsing problem in Csharp

Posted 22 March 2019 - 04:40 AM

First off im new here, im posting my entire code that is not working and ive spent days on it.
Im not asking for anyone to fix the code, but rather suggestions on how to fix it!



 

String values = DateRangePicker1.Value.ToString();
                String startDate = values.Substring(0, 8);
                String endDate = values.Substring(11, 8);
                DateTime date = DateTime.ParseExact(startDate, "M/d/yyyy", CultureInfo.InvariantCulture);
                DateTime date1 = DateTime.ParseExact(endDate, "M/d/yyyy", CultureInfo.InvariantCulture);
                //DateTime datep = DateTime.ParseExact(startDate, "MM/dd/yyyy", CultureInfo.InvariantCulture);
                //DateTime datep1 = DateTime.ParseExact(endDate, "MM/dd/yyyy", CultureInfo.InvariantCulture);
                String newSDate = date.ToString();
                String newEDate = date1.ToString();
                String finalSDate = newSDate.Substring(0, 10);
                String finalEDate = newEDate.Substring(0, 10);

 List<ChartData> data1 = new List<ChartData>();
                string connetionString;
                MySqlConnection cnn1;
                connetionString = "BLANK FOR SECURITY";
                cnn1 = new MySqlConnection(connetionString);
                cnn1.Open();
                MySqlDataAdapter da1 = new MySqlDataAdapter("SELECT SUBSTRING(date_time,1,10), sum(Total), sum(Total_ly),  AVG ((Total + Total_ly)/2) FROM Transaction WHERE Substring(date_time,1,10) between @param1 AND @param2 Group By date_time Having sum(Total)<>0; ", cnn1);
                //MySqlDataAdapter da = new MySqlDataAdapter("SELECT * FROM Transaction WHERE date_time = @param1 Group By date_time ; ", cnn);
                //MySqlDataAdapter da = new MySqlDataAdapter($"SELECT SUBSTRING({date_time},1,10), sum({Total}), sum({Total_ly}),  AVG ({(Total + Total_ly) / 2}) FROM Transaction WHERE Substring({date_time/},1,10)= @param1 Group By date_time Having sum({Total})<>0; ");
                //MySqlDataAdapter daPrediction = new MySqlDataAdapter("SELECT  AVG ((Total + Total_ly)/2) as ny From Transaction Group by TransNo; ", cnn)/;
                //String day = Datepicker1.Value.ToString();
                da1.SelectCommand.Parameters.AddWithValue("@param1", finalSDate);
                da1.SelectCommand.Parameters.AddWithValue("@param2", finalEDate);
                DataTable table1 = new DataTable();



ERROR

System.FormatException: String was not recognized as a valid DateTime. at System.DateTimeParse.ParseExact(String s, String format, DateTimeFormatInfo dtfi, DateTimeStyles style) at System.DateTime.ParseExact(String s, String format, IFormatProvider provider)

Thanks in advance !

Is This A Good Question/Topic? 0
  • +

Replies To: Parsing problem in Csharp

#2 andrewsw   User is offline

  • quantum multiprover
  • member icon

Reputation: 6775
  • View blog
  • Posts: 27,938
  • Joined: 12-December 12

Re: Parsing problem in Csharp

Posted 22 March 2019 - 04:48 AM

What specific line causes the error? You use ParseExact twice.
What is the value of 'values' when it fails? And startDate and endDate?

The most obvious and likely reason that it fails is that the date it is attempting to parse is not in the exact format "M/d/yyyy".

Be careful that Transaction is a MySql reserved word and should either be delimited with backticks or, preferably, renamed.
Was This Post Helpful? 1
  • +
  • -

#3 Sheepings   User is offline

  • Senior Programmer
  • member icon

Reputation: 209
  • View blog
  • Posts: 1,182
  • Joined: 05-December 13

Re: Parsing problem in Csharp

Posted 22 March 2019 - 07:41 AM

Your approach here is wrong.
01
String values = DateRangePicker1.Value.ToString();
02
                String startDate = values.Substring(0, 8);
03
                String endDate = values.Substring(11, 8);

This will give you 22/03/20 as opposed to 2020. And so, you will get a date time system format exception here ::
DateTime date = DateTime.ParseExact(startDate, "M/d/yyyy", CultureInfo.InvariantCulture);
because the date is not in the appropriate format.

See https://www.c-sharpc...rp-programming1 for date time formats. Note :: String startDate = values.Substring(0, 8); will only give you the first yy digits of the yyyy required, with the last 2 digits also cut by your substring.

Try this ::
        public Form1()
        {
            InitializeComponent();
            TimeMain();
        }
        public CultureInfo provider = CultureInfo.InvariantCulture;
        public string myDate, dtFormat;
        public DateTime DateIs;
        public void TimeMain()
        {
            myDate = DateRangePicker1.Value.ToString().Substring(0,10);
            dtFormat = "dd/mm/yyyy";
            try
            {
                DateIs = DateTime.ParseExact(myDate, dtFormat, provider);
                Console.WriteLine("{0} this makes the date {1}.", myDate, DateIs.ToString());
            }
            catch (FormatException)
            {
                Console.WriteLine("Format error, sort your self out", myDate);
            }
        }
Output ::
22/03/2019 this makes the date 22/01/2019 00:03:00.

If you provide the time for a time string variable, you can do the same for it as I've done with the date. You can then substring the time, giving you only a time variable.

Hope this helps :)

EDIT :: I also forgot to mention that invariant culture requires two-digit month, so this is not going to work "M/d/yyyy", CultureInfo.InvariantCulture); for you.

dd -> Represents the day of the month as a number from 01 through 31.

MM Month number with leading zero(eg.04)

Your format is M Month number(eg.3) and d -> Represents the day of the month as a number from 1 through 31.

This post has been edited by Sheepings: 22 March 2019 - 09:02 AM

Was This Post Helpful? 1
  • +
  • -

#4 Skydiver   User is offline

  • Code herder
  • member icon

Reputation: 6818
  • View blog
  • Posts: 23,194
  • Joined: 05-May 12

Re: Parsing problem in Csharp

Posted 22 March 2019 - 10:56 AM

Actually, why are even trying to parse the selected values? Why are you string-ly typed?

Why do you even need to get the result of your DateRanegPicker as a string and then go back to converting that string into a pair of DateTimes? I bet that Value property is some kind of struct or class similar to the one in this CodeProject DateRangePicker. It should have a From and To or Start and End pair of DateTime properties.

The built-in WinForm MonthCalendar control has Selectionstart and Selectionend properties: How to: Select a Range of Dates in the Windows Forms MonthCalendar Control
Was This Post Helpful? 1
  • +
  • -

#5 Sheepings   User is offline

  • Senior Programmer
  • member icon

Reputation: 209
  • View blog
  • Posts: 1,182
  • Joined: 05-December 13

Re: Parsing problem in Csharp

Posted 22 March 2019 - 06:44 PM

juniordev101, can you provide the link to the control you used for this DateRangePicker? It would really help to better give you the best answer to your problem. I'm assuming this is the one from CodeProject?
Was This Post Helpful? 1
  • +
  • -

#6 juniordev101   User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 10
  • Joined: 22-March 19

Re: Parsing problem in Csharp

Posted 24 March 2019 - 04:49 AM

So i dont think i explained myself to well, my code works fine for any dates in the single form i.e. 01/03/2019 - 09/03/2019, its
when the date is in double digits its giving the parse error.

@sheepings i get what your saying but this will not work in my case as the datetimepicker reads the start and end date into one string
Was This Post Helpful? 0
  • +
  • -

#7 juniordev101   User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 10
  • Joined: 22-March 19

Re: Parsing problem in Csharp

Posted 24 March 2019 - 04:55 AM

View PostSheepings, on 22 March 2019 - 06:44 PM, said:

juniordev101, can you provide the link to the control you used for this DateRangePicker? It would really help to better give you the best answer to your problem. I'm assuming this is the one from CodeProject?



Its from SYNCFUSION its the community edition which is free
https://help.syncfus...datetime-format

I have to use this one, i know the built in one is much easier!
Was This Post Helpful? 0
  • +
  • -

#8 juniordev101   User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 10
  • Joined: 22-March 19

Re: Parsing problem in Csharp

Posted 24 March 2019 - 05:12 AM

The standard formats are listed as follows

Format Name

Formats

default

"M/d/yyyy"

Short

“d M, y”

Medium

“d MM, y”

Full

“dddd, d MMMM, yy”

UTC

“yyyy-MM-dd”

By default ‘en-US’ culture date format is “M/d/yyyy”.

So im thinking now if i change the format to UTC this should eliminate the problem ??
Was This Post Helpful? 0
  • +
  • -

#9 juniordev101   User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 10
  • Joined: 22-March 19

Re: Parsing problem in Csharp

Posted 24 March 2019 - 07:28 AM

Hi guys, thanks for everyone's input !
Problem is now solved
By changing localization settings on daterangepicker to format the date
This done the trick :bananaman:
Was This Post Helpful? 0
  • +
  • -

#10 Sheepings   User is offline

  • Senior Programmer
  • member icon

Reputation: 209
  • View blog
  • Posts: 1,182
  • Joined: 05-December 13

Re: Parsing problem in Csharp

Posted 24 March 2019 - 11:47 AM

View Postjuniordev101, on 24 March 2019 - 12:12 PM, said:

So im thinking now if i change the format to UTC this should eliminate the problem ??

Already answered you here and told you so ::

View PostSheepings, on 22 March 2019 - 02:41 PM, said:

EDIT :: I also forgot to mention that invariant culture requires two-digit month, so this is not going to work "M/d/yyyy", CultureInfo.InvariantCulture); for you.

So yes, if you mean by what you call UTC, yes, then that will work for InvariantCulture.

View Postjuniordev101, on 24 March 2019 - 11:49 AM, said:

So i dont think i explained myself to well, my code works fine for any dates in the single form i.e. 01/03/2019 - 09/03/2019, its
when the date is in double digits its giving the parse error.
@sheepings i get what your saying but this will not work in my case as the datetimepicker reads the start and end date into one string

Firstly, I am not familiar with the expression "single form". And what you quoted are double values if that was the appropriate name to call them... Second, what do you mean won't work? I tested the code I gave you and it worked pretty good for me. While I didn't have a date range picker, I had a dateTimePicker and so, while the concept is longer for you, the principle approach is the same. In your case, you simply substring your way though the range of dates providing you pass the correct culture. I feel my example is a good one to follow. In fact, I wrote it similar to how Microsoft wrote there's.

View Postjuniordev101, on 24 March 2019 - 11:55 AM, said:

Its from SYNCFUSION its the community edition which is free
https://help.syncfus...datetime-format

Skydiver See link ^ and https://help.syncfus...cker/date-range

This post has been edited by Sheepings: 24 March 2019 - 11:48 AM

Was This Post Helpful? 0
  • +
  • -

#11 Skydiver   User is offline

  • Code herder
  • member icon

Reputation: 6818
  • View blog
  • Posts: 23,194
  • Joined: 05-May 12

Re: Parsing problem in Csharp

Posted 24 March 2019 - 05:29 PM

View Postjuniordev101, on 24 March 2019 - 07:55 AM, said:

Its from SYNCFUSION its the community edition which is free
https://help.syncfus...datetime-format

I have to use this one, i know the built in one is much easier!

Ouch! It's at end of life...

Quote

With the release of version 14.4.0.20, Syncfusion no longer develops new controls for LightSwitch. However, we will support our existing controls, including updates, patches, and downloads of previous versions.

according to their home page banner.

My condolences to you for having to continue to write code for it.

Anyway, it looks like you are forced to be string-ly typed because from what I can skim from the documentation, the data comes back to you as the Value of an <input> element.

My recommendation is to first split the string between the start date and end date by looking for the '-' which separates them. Very like the String.Split() should be sufficient. Unless the input dates come in with parts separated by dashes instead of slashes, this will be more robust than using Substring() to get exact character counts and indexes.

Once you have the two strings, then it's actually better to use DateTime.TryParseExact() passing in a few of the potentially expected date formats.

In general, in C# it is better to use the TryParse() variant instead of the Parse() variants of the various types. This is because exceptions are expensive, and you shouldn't be using exceptions for flow control.
Was This Post Helpful? 1
  • +
  • -

Page 1 of 1