Avatar of sana khan
sana khan
Flag for India asked on

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
ASP.NETDatabases

Avatar of undefined
Last Comment
sana khan

8/22/2022 - Mon
Kimputer

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
it_saige

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 Kline

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;
This is the best money I have ever spent. I cannot not tell you how many times these folks have saved my bacon. I learn so much from the contributors.
rwheeler23
sana khan

ASKER
I am sure of database date that is in variable dt1 but i am not sure about the system date.
Shaun Kline

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

DateTime dt2 = DateTime.Today;
ASKER CERTIFIED SOLUTION
ste5an

THIS SOLUTION ONLY AVAILABLE TO MEMBERS.
View this solution by signing up for a free trial.
Members can start a 7-Day free trial and enjoy unlimited access to the platform.
See Pricing Options
Start Free Trial
GET A PERSONALIZED SOLUTION
Ask your own question & get feedback from real experts
Find out why thousands trust the EE community with their toughest problems.
sana khan

ASKER
Error is giving on this line:

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

Open in new window

⚡ FREE TRIAL OFFER
Try out a week of full access for free.
Find out why thousands trust the EE community with their toughest problems.
it_saige

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-
sana khan

ASKER
I got the solution using this code