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?

[Product update] Infrastructure Analysis Tool is now available with Business Accounts.Learn More

x
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

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
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
Powerful Yet Easy-to-Use Network Monitoring

Identify excessive bandwidth utilization or unexpected application traffic with SolarWinds Bandwidth Analyzer Pack.

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
ste5anSenior 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

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
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
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
ASP.NET

From novice to tech pro — start learning today.