Showing errors of date as "string was not recognized as a valid datetime"

sana khan
sana khan used Ask the Experts™
on
 public void databind2()
    {
        SqlCommand Comm1 = new SqlCommand("select FORMAT(deadlineDate,'dd-MM-yyyy') from FormDetails where FormId=" + FormIDs.Client_BulkPostCard + " and Edition_Id='" + Session["Edition_ID"].ToString() + "'", con);
        con.Open();
        SqlDataReader dr = Comm1.ExecuteReader();
        if (dr.Read())
        {
            Label1.Text = dr[0].ToString();          
        }

        DateTime dt1 = DateTime.Parse(Label1.Text);
        DateTime dt2 = DateTime.Parse(DateTime.Now.ToString());

        int days = (dt1 - dt2).Days;

        if (days > 0)
        {
            lblNoOfDays.Text = days + " DAYS LEFT";
        }
        else
        {
            lblNoOfDays.Text = "DEADLINE PASSED";
        }
        con.Close();
    }

Open in new window


The dt1 date is coming from database in the format as dd-mm-yyyy(31-12-17) but the current date which is stored in dt2 is coming from system as dd-mmm-yyyy(01-nov-17)
so it showing error . Please help me solving this issue using Asp.Net
Comment
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®

Commented:
If you are really really sure the input is always the same format, try this:

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

Commented:
One of your date's cannot be parsed.  Might want to consider using ParseExact; e.g. -
using System;
using System.Globalization;

namespace EE_Q29065846
{
    class Program
    {
        static void Main(string[] args)
        {
            string date1 = "31-12-17", date2 = "01-nov-17";
            DateTime dt1 = DateTime.ParseExact(date1, new string[] { "dd-MM-yy", "dd-MM-yyyy" }, CultureInfo.CurrentCulture, DateTimeStyles.None);
            DateTime dt2 = DateTime.ParseExact(date2, new string[] { "dd-MMM-yy", "dd-MMM-yyyy", "dd-MMMM-yy", "dd-MMMM-yyyy" }, CultureInfo.CurrentCulture, DateTimeStyles.None);

            int days = (dt1 - dt2).Days;
            if (days > 0)
                Console.WriteLine("{0} DAYS LEFT", days);
            else
                Console.WriteLine("DEADLINE PASSED");
            Console.ReadLine();
        }
    }
}

Open in new window


-saige-
Shaun KlineLead Software Engineer

Commented:
Why perform this line?

DateTime dt2 = DateTime.Parse(DateTime.Now.ToString());

DateTime.Now is a DateTime value which you could then use in your calculation of days:

int days = (dt1 - DateTime.Now).Days;
Ensure you’re charging the right price for your IT

Do you wonder if your IT business is truly profitable or if you should raise your prices? Learn how to calculate your overhead burden using our free interactive tool and use it to determine the right price for your IT services. Start calculating Now!

Author

Commented:
I am sure of database date that is in variable dt1 but i am not sure about the system date.
Shaun KlineLead Software Engineer

Commented:
If you need to assign "today" to dt2, you can just do:

DateTime dt2 = DateTime.Today;
Senior Developer
Commented:
1. Use parameterized queries. Your SQL string building allows SQL ínjection.
2. Formatting is a front-end task. Thus don't do it on the SQL server side.
3. Work with strong types to ensure data integrity also in your front-end.
4. Free instances of classes implemeting IDisposable.
5. Use a consistent naming schemes. FormId and Edition_Id is hard to memorize, where you need an underscore.

E.g.

public void databind2()
{
    const string SQL_SELECT = "SELECT deadlineDate FROM FormDetails WHERE FormID = @FormID" AND Edition_ID = @EditionID;"
    using (SqlCommand cmd = new SqlCommand())
    {
        cmd.Connection = this.con;
        cmd.Text = SQL_SELECT;
        command.Parameters.Add("@FormID", SqlDbType.Int);
        command.Parameters.Add("@EditionID", SqlDbType.NVarChar);
        command.Parameters["@FormID"].Value = FormIDs.Client_BulkPostCard;
        command.Parameters["@EditionID"].Value = Session["Edition_ID"].ToString();
        try
        {
            con.Open();
            DateTime? deadlineDate = cmd.ExecuteScalar() as DateTime?;
            if (deadlineDate.HasValue)
            {
                Label1.Text = deadlineDate.ToString();
                int days = (deadlineDate - DateTime.Now()).Days;
                if (days > 0)
                {
                    lblNoOfDays.Text = days + " DAYS LEFT";
                }
                else
                {
                    lblNoOfDays.Text = "DEADLINE PASSED";
                }
            }
            else
            {
                lblNoOfDays.Text = "NO DEADLINE.";
            }

            con.Close();
        }
        catch (Exception e)
        {
            // TODO: Add error handling.
        }
    }
}

Open in new window

Author

Commented:
Error is giving on this line:

DateTime dt1 = DateTime.Parse(Label1.Text);

Open in new window

Commented:
As I stated, your date (or dates) cannot be parsed...  Use ParseExact.

Proof of concept -
using System;
using System.Globalization;

namespace EE_Q29065846
{
    class Program
    {
        static void Main(string[] args)
        {
            string date1 = "31-12-17", date2 = "01-nov-17";
            ParseDates(date1, date2);
            ParseExactDates(date1, date2);
            Console.ReadLine();
        }

        static void ParseDates(string date1, string date2)
        {
            try
            {
                DateTime dt1 = DateTime.Parse(date1);
                Console.WriteLine("Date1 parsed - {0}", dt1);
            }
            catch (Exception ex)
            {
                Console.WriteLine("Error parsing date1 - {0}", ex.Message);
            }

            try
            {
                DateTime dt2 = DateTime.Parse(date2);
                Console.WriteLine("Date2 parsed - {0}", dt2);
            }
            catch (Exception ex)
            {
                Console.WriteLine("Error parsing date2 - {0}", ex.Message);
            }
        }

        static void ParseExactDates(string date1, string date2)
        {
            try
            {
                DateTime dt1 = DateTime.ParseExact(date1, new string[] { "dd-MM-yy", "dd-MM-yyyy" }, CultureInfo.CurrentCulture, DateTimeStyles.None);
                Console.WriteLine("Date1 parsed - {0}", dt1);
            }
            catch (Exception ex)
            {
                Console.WriteLine("Error parsing date1 - {0}", ex.Message);
            }

            try
            {
                DateTime dt2 = DateTime.ParseExact(date2, new string[] { "dd-MMM-yy", "dd-MMM-yyyy", "dd-MMMM-yy", "dd-MMMM-yyyy" }, CultureInfo.CurrentCulture, DateTimeStyles.None);
                Console.WriteLine("Date2 parsed - {0}", dt2);
            }
            catch (Exception ex)
            {
                Console.WriteLine("Error parsing date2 - {0}", ex.Message);
            }
        }
    }
}

Open in new window

Produces the following output -Capture.PNG
-saige-

Author

Commented:
I got the solution using this code

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial