datetime.parse not working.

Aravind Ranganathan
Aravind Ranganathan used Ask the Experts™
on
dateshit.JPG

everything looks right why is it still throwing that stupid error, i hate strings and date they need to do something regarding this :(
Comment
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®
Chinmay PatelChief Technology Ninja
Distinguished Expert 2018

Commented:
Hi Aravind,

Please post your code using
 tags that makes it easier for experts to help you.

And I tried this code and it worked just fine.

[code]
string textDate = "04/01/2019 12:01:32 PM";
		DateTime myDate = DateTime.ParseExact(textDate, "MM/dd/yyyy HH:mm:ss tt", CultureInfo.InvariantCulture);

Open in new window


Regards,
Chinmay.
Most Valuable Expert 2015
Distinguished Expert 2018

Commented:
Parse will do it:

string textDate = "04/01/2019 12:01:32 PM";
DateTime trueDate =DateTime.Parse(textDate);

Open in new window

or, if you prefer to be specific:

string textDate = "04/01/2019 12:01:32 PM";
System.Globalization.CultureInfo provider = new System.Globalization.CultureInfo("en-US");
DateTime date =DateTime.Parse(textDate, provider);

Open in new window

Result:
2019-04-01 12:01:32

Open in new window

Aravind RanganathanWindows Application Developer

Author

Commented:
@Chimay Patel
here is the code

.aspx
    <script type="text/javascript">



        function ShowTime() {



            var dt = new Date();
            var n = dt.toLocaleDateString("en-029");
            var w = dt.toLocaleTimeString();
            var fullDate = n + ' ' + w;

            document.getElementById("<%= todaydate.ClientID %>").value = fullDate



        window.setTimeout("ShowTime()", 0);



    }



</script>

<script type="text/javascript">



    window.setTimeout("ShowTime()", 0);



</script>

Open in new window


.cs
  protected void btn_Create_Click(object sender, EventArgs e)
        {
            replaceblankvalueswithzero();
            using (SqlConnection db = new SqlConnection(con))
            {

                db.Open();
                string textDate = todaydate.Text.ToString();
                DateTime myDate = DateTime.ParseExact(textDate, "MM/dd/yyyy HH:mm:ss tt", CultureInfo.InvariantCulture);
                //DateTime myDate = DateTime.ParseExact(todaydate.Text, "MM/dd/yyyy hh:mm:ss tt", CultureInfo.InvariantCulture);
                string insert = "insert into dbo.Waste ([Plant],[Department],[Line],[Date],[Shift] ,[Operator] ,[Item_Code],[Item_Desc],[1st_Quality],[Un_coated_rework] ,[CoatedRework] ,[Purge_Out_UC_Rework],[Seconds] ,[TBD],[Floor_Waste] ,[Machine_Waste],[Purge_Out],[Roller_Scraper_Waste],[Extraordinary_Waste],[NOFCR],[Outdated],[Actual_Waste_Shipment],[Sub_Item],[Batch_ID],[Explanation_Details],[Approved],[Submited]) values ('" + PlantVal.ToString() + "','" + Department.SelectedValue.ToString() + "','" + LineValues.SelectedValue.ToString() + "','" + myDate + "','" + ShiftValues.SelectedValue.ToString() + "','" + Operator.Text + "','" + itemcode.Text + "','" + itemdesc.Text + "','" + firststQuality.Text + "','" + uncoated.Text + "','" + coatedrework.Text + "','" + purgeoutuc.Text + "','" + seconds.Text + "','" + tbd.Text + "','" + floorwaste.Text + "','" + machinewaste.Text + "','" + purgeout.Text + "','" + rollerscrapper.Text + "','" + extraordinary.Text + "','" + nofcr.Text + "','" + outdated.Text + "','" + actualwaste.Text + "','" + subitem.Text + "','" + batchid.Text + "','" + explanationdetails.Text + "','" + 0 + "','" + 1 + "')";
                SqlCommand cmd = new SqlCommand(insert, db);
                try
                {

                    int m = cmd.ExecuteNonQuery();
                    if (m != 0)
                    {
                        ClientScript.RegisterStartupScript(this.GetType(), "myalert", "alert('" + "Inserted into the database successfully" + "');", true); ;
                    }
                    else
                    {
                        ClientScript.RegisterStartupScript(this.GetType(), "myalert", "alert('" + "Data insert was not succesful please contact" + "');", true);
                    }
                }
                catch (Exception ex)
                {
                    PageLogger.Debug("DEBUG|" + ex.Message);
                    PageLogger.Error("ERROR|" + ex.StackTrace);
                    lblPopUpError.Text = ex.Message;
                }
            }
            PopulateGridview("empty", "empty");
            clearvalues();
        }

Open in new window

Learn SQL Server Core 2016

This course will introduce you to SQL Server Core 2016, as well as teach you about SSMS, data tools, installation, server configuration, using Management Studio, and writing and executing queries.

Aravind RanganathanWindows Application Developer

Author

Commented:
@Gustav Brock

Parse didnt work still getting the same error:

stupiddate.JPG

Commented:
Your filter is incorrect.  It needs to use: "MM/dd/yyyy hh:mm:ss tt".  You also need to pay mind to what Gustav has stated.  If your culture settings are not correct, then you won't be able to parse the date either.

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

namespace EE_Q29141364
{
    class Program
    {
        static void Main(string[] args)
        {
            var date = default(DateTime);
            var culture = new CultureInfo("en-US");
            DateTime.TryParseExact("04/01/2019 12:01:32 PM", "MM/dd/yyyy hh:mm:ss tt", culture, DateTimeStyles.None, out date);
            Console.WriteLine(date);
            Console.ReadLine();
        }
    }
}

Open in new window

Produces the following output -Capture.PNG-saige-
Most Valuable Expert 2015
Distinguished Expert 2018

Commented:
You are making it way too hard for yourself, as all you need is a string expression of the date value, and this should be ISO formatted, no AM/PM:

DateTime trueDate = DateTime.Now;
System.Globalization.CultureInfo provider = System.Globalization.CultureInfo.InvariantCulture;
string myDate = trueDate.ToString("yyyy-MM-dd HH:mm:ss", provider);
string insert = "insert into dbo.Waste …<snip> ..; 

Open in new window

The answer for your existing code is that the hours format should use the 12 hour string (hh) instead of the 24 hour string (HH) as both @Gustav and @saige have stated.

Further, I'm wondering why you are parsing the date at all as you're ingesting the exact same value the postback provides without validation or transformation. Looking at your debugger output the date appears to already be a string in the correct format; have you tried simply using that instead of parsing it?

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