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

 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
sana khanAsked:
Who is Participating?
 
ste5anConnect With a Mentor Senior DeveloperCommented:
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

0
 
KimputerCommented:
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
0
 
it_saigeDeveloperCommented:
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-
0
Improve Your Query Performance Tuning

In this FREE six-day email course, you'll learn from Janis Griffin, Database Performance Evangelist. She'll teach 12 steps that you can use to optimize your queries as much as possible and see measurable results in your work. Get started today!

 
Shaun KlineLead Software EngineerCommented:
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;
0
 
sana khanAuthor Commented:
I am sure of database date that is in variable dt1 but i am not sure about the system date.
0
 
Shaun KlineLead Software EngineerCommented:
If you need to assign "today" to dt2, you can just do:

DateTime dt2 = DateTime.Today;
0
 
sana khanAuthor Commented:
Error is giving on this line:

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

Open in new window

0
 
it_saigeDeveloperCommented:
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-
0
 
sana khanAuthor Commented:
I got the solution using this code
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.