• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 749
  • Last Modified:

need to convert datetime to string.

Server Error in '/OmegaLove_CS/OL_Web' Application.
--------------------------------------------------------------------------------

String was not recognized as a valid DateTime.
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

Exception Details: System.FormatException: String was not recognized as a valid DateTime.

Source Error:


Line 81:             selected_date = values[this.UniqueID.ToString()];
Line 82:             sel_date_convert = values[this.UniqueID.ToString() + "_conv"];
Line 83:             date_picked = System.DateTime.Parse(sel_date_convert).Date;
Line 84:             Month = date_picked.Month;
Line 85:             Day = date_picked.Day;
 

Source File: C:\inetpub\wwwroot\OmegaLove_CS\OL_DateTimePicker\mm_datepicker.cs    Line: 83

Stack Trace:


[FormatException: String was not recognized as a valid DateTime.]
   System.DateTimeParse.Parse(String s, DateTimeFormatInfo dtfi, DateTimeStyles styles) +2834318
   mm_date.datepicker.LoadPostData(String postDataKey, NameValueCollection values) in C:\inetpub\wwwroot\OmegaLove_CS\OL_DateTimePicker\mm_datepicker.cs:83
   System.Web.UI.Page.ProcessPostData(NameValueCollection postData, Boolean fBeforeLoad) +346
   System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +1743

 

using System;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.ComponentModel;
using System.Collections;
using System.Collections.Specialized;
using System.Text;
 
namespace mm_date
{
    /// <summary>
    /// DatePicker - Generates drop down select objects for date selection
    /// Client side javascript ensures only valid date returned.
    /// </summary>
 
    [DefaultProperty("Text"),
        ToolboxData("<{0}:datepicker runat=server></{0}:datepicker>")]
 
    public class datepicker : System.Web.UI.WebControls.WebControl, System.Web.UI.IPostBackDataHandler
    {
        //Declarations
        private int begyear = System.DateTime.Today.Year;
        private int endyear = System.DateTime.Today.Year;
        private int date_mode = 1;
        private int form_level = 0;
        private DateTime initial_date = System.DateTime.Today;
        private int sel_month = System.DateTime.Today.Month;
        private int sel_day = System.DateTime.Today.Day;
        private int sel_year = System.DateTime.Today.Year;
        private int picked_month = 0;
        private int picked_day = 0;
        private int picked_year = 0;
        private string selected_date;
        private string sel_date_convert;
        private DateTime date_picked;
        private string control = "Datepicker";
 
        //Define Properties
 
        //Control Release & About
        [Bindable(false),
        Category("About"),
        DefaultValue(""),
        Description("Control:  Datepicker\n" +
            "Version:  Ver 1.01 - 12/01/2003\n" +
            "Author:   Michael McLain\n" +
            "Desc:      Date dropdown selection control\n")]
 
        public string Control
        {
            get
            {
                return control;
            }
            set
            {
                control = value;
            }
        }
 
 
        //Posted Date Returned
        [Bindable(true),
        Category("Returned Values"),
        DefaultValue(""),
        Description("Returned date selected (string)")]
        public string Selected_Date
        {
            get
            {
                return selected_date;
            }
            set
            {
                selected_date = value;
            }
        }
 
        public bool LoadPostData(String postDataKey, NameValueCollection values)
        {
            selected_date = values[this.UniqueID.ToString()];
            sel_date_convert = values[this.UniqueID.ToString() + "_conv"];
            date_picked = System.DateTime.Parse(sel_date_convert).Date;
            Month = date_picked.Month;
            Day = date_picked.Day;
            Year = date_picked.Year;
            if (this.EnableViewState)
            {
                this.initial_date = date_picked;
            }
            return false;
        }
 
        public void RaisePostDataChangedEvent()
        {
        }
 
        //Returned date in datetime format
        [Bindable(true),
        Category("Returned Values"),
        DefaultValue(""),
        Description("Returned date selected (datetime)")]
        public DateTime Date_Picked
        {
            get
            {
                return date_picked;
            }
            set
            {
                date_picked = value;
            }
        }
 
        //Returned Month
        [Bindable(false),
        Category("Returned Values"),
        DefaultValue(""),
        Description("Returned month selected (int)")]
        public int Month
        {
            get
            {
                return picked_month;
            }
            set
            {
                picked_month = value;
            }
        }
 
        //Returned Day
        [Bindable(false),
        Category("Returned Values"),
        DefaultValue(""),
        Description("Returned day selected (int)")]
        public int Day
        {
            get
            {
                return picked_day;
            }
            set
            {
                picked_day = value;
            }
        }
 
        //Returned year
        [Bindable(false),
        Category("Returned Values"),
        DefaultValue(""),
        Description("Returned year selected (int)")]
        public int Year
        {
            get
            {
                return picked_year;
            }
            set
            {
                picked_year = value;
            }
        }
 
        //Begin Year
        [Bindable(true),
        Category("Setup Values"),
        DefaultValue(""),
        Description("Beginning Year Select Range")]
        public int YearRange_Start
        {
            get
            {
                return begyear;
            }
 
            set
            {
                begyear = value;
            }
        }
 
        //End Year
        [Bindable(true),
        Category("Setup Values"),
        DefaultValue(""),
        Description("Ending Year Select Range")]
        public int YearRange_End
        {
            get
            {
                return endyear;
            }
 
            set
            {
                endyear = value;
            }
        }
 
        //Initial date selected
        [Bindable(true),
        Category("Setup Values"),
        DefaultValue(""),
        Description("Initial selected date")]
        public DateTime Initial_Date
        {
            get
            {
                return initial_date;
            }
 
            set
            {
                initial_date = value;
            }
        }
 
        //Date format returned (in string format)
        //Included for backward compatibility to Classic ASP version
        [Bindable(true),
        Category("Setup Values"),
        DefaultValue(""),
        Description("Date format returned in (Selected_Date).\n1 - MM/DD/YYYY\n2 - DD/MM/YYYY\n3 - YYYYMMDD\n4 - universal format")]
        public int Date_Mode
        {
            get
            {
                return date_mode;
            }
 
            set
            {
                date_mode = value;
            }
        }
 
        //Form level index to allow handling multiple forms per page.
        [Bindable(false),
        Category("Setup Values"),
        DefaultValue(""),
        Description("Document form index level")]
        public int Form_Level
        {
            get
            {
                return form_level;
            }
 
            set
            {
                form_level = value;
            }
        }
 
        /// <summary>
        /// Render this control to the output parameter specified.
        /// </summary>
        /// <param name="output"> The HTML writer to write out to </param>
        protected override void Render(HtmlTextWriter output)
        {
            string cid = this.UniqueID.ToString();
            string isSelected = "";
            string docref = "document.forms[" + this.form_level.ToString() + "]." + cid;
            string onchg = " onChange=\"tg_mm_setdays('" + docref + "'," + date_mode.ToString() + ")\"";
            string objinit = "<script language=javascript>tg_mm_setdays('" + docref + "'," + date_mode.ToString() + ")</script>";
 
            //Build control style
            string ostyle = "";
            string c_ostyle = "";
            string ostylevalue = "";
            int stylecount = this.Style.Count;
            foreach (string stmp in this.Style.Keys)
            {
                ostylevalue = this.Style[stmp].ToString();
                c_ostyle = c_ostyle + stmp + ": " + ostylevalue + "; ";
            }
 
            StringBuilder s = new StringBuilder();
 
            //Set component container if applied style
            //Container used to handle grid layout mode
            if (c_ostyle != "")
            {
                s.Append("<div style=\"" + c_ostyle + "\">");
            }
 
            //Build select drop down styles
            string color = "";
            if (!this.ForeColor.IsEmpty)
            {
                color = this.ForeColor.Name;
                if (color != "")
                {
                    if (!this.ForeColor.IsNamedColor && !this.ForeColor.IsSystemColor)
                    {
                        color = "#" + color.Substring(2, 6);
                    }
                }
            }
            string backcolor = "";
            if (!this.BackColor.IsEmpty)
            {
                backcolor = this.BackColor.Name;
                if (backcolor != "")
                {
                    if (!this.BackColor.IsNamedColor && !this.BackColor.IsSystemColor)
                    {
                        backcolor = "#" + backcolor.Substring(2, 6);
                    }
                }
            }
            string fontname = this.Font.Name;
            string fontsize = this.Font.Size.ToString();
            string cssclass = this.CssClass;
            bool fontstyle = this.Font.Italic;
            bool fontbold = this.Font.Bold;
            bool underline = this.Font.Underline;
            bool overline = this.Font.Overline;
            bool strikeout = this.Font.Strikeout;
            string textdecoration = "";
 
            //TEXT-DECORATION: underline overline line-through
            if (underline || overline || strikeout)
            {
                textdecoration = "TEXT-DECORATION: ";
                if (underline)
                {
                    textdecoration = textdecoration + "underline ";
                }
                if (overline)
                {
                    textdecoration = textdecoration + "overline ";
                }
                if (strikeout)
                {
                    textdecoration = textdecoration + "strikeout ";
                }
                textdecoration = textdecoration + ";";
            }
 
            if (cssclass != "")
            {
                cssclass = " class=\"" + cssclass + "\"";
            }
            ostyle = " style=\"";
            if (fontname != "")
            {
                ostyle = ostyle + "FONT-FAMILY: " + fontname + ";";
            }
            if (fontsize != "")
            {
                ostyle = ostyle + "FONT-SIZE: " + fontsize + ";";
            }
            if (fontstyle)
            {
                ostyle = ostyle + "FONT-STYLE: italic;";
            }
            if (fontbold)
            {
                ostyle = ostyle + "FONT-WEIGHT: bold;";
            }
 
            if (color != "")
            {
                ostyle = ostyle + "COLOR: " + color + ";";
            }
 
            if (backcolor != "")
            {
                ostyle = ostyle + "BACKGROUND-COLOR: " + backcolor + ";";
            }
 
            if (textdecoration != "")
            {
                ostyle = ostyle + textdecoration;
            }
            ostyle = ostyle + "\"" + cssclass;
 
            //Build Month Dropdown
            sel_month = initial_date.Month;
            sel_day = initial_date.Day;
            sel_year = initial_date.Year;
 
            //Determine days in Month
            DateTime wrkdate = initial_date.Date;
            int daysinmonth = 0;
            while (sel_month == wrkdate.Month)
            {
                daysinmonth = wrkdate.Day;
                wrkdate = wrkdate.AddDays(1);
            }
            s.Append("\n<select name=\"" + cid + "_month\"" + onchg + ostyle + ">\n");
            isSelected = checkselected(1, sel_month);
            s.Append("<option value=1" + isSelected + ">Jan</option>\n");
            isSelected = checkselected(2, sel_month);
            s.Append("<option value=2" + isSelected + ">Feb</option>\n");
            isSelected = checkselected(3, sel_month);
            s.Append("<option value=3" + isSelected + ">Mar</option>\n");
            isSelected = checkselected(4, sel_month);
            s.Append("<option value=4" + isSelected + ">Apr</option>\n");
            isSelected = checkselected(5, sel_month);
            s.Append("<option value=5" + isSelected + ">May</option>\n");
            isSelected = checkselected(6, sel_month);
            s.Append("<option value=6" + isSelected + ">Jun</option>\n");
            isSelected = checkselected(7, sel_month);
            s.Append("<option value=7" + isSelected + ">Jul</option>\n");
            isSelected = checkselected(8, sel_month);
            s.Append("<option value=8" + isSelected + ">Aug</option>\n");
            isSelected = checkselected(9, sel_month);
            s.Append("<option value=9" + isSelected + ">Sep</option>\n");
            isSelected = checkselected(10, sel_month);
            s.Append("<option value=10" + isSelected + ">Oct</option>\n");
            isSelected = checkselected(11, sel_month);
            s.Append("<option value=11" + isSelected + ">Nov</option>\n");
            isSelected = checkselected(12, sel_month);
            s.Append("<option value=12" + isSelected + ">Dec</option>\n");
            s.Append("</select>\n");
 
            //Build Day Dropdown
            s.Append("\n<select name=\"" + cid + "_day\"" + onchg + ostyle + ">\n");
            int i;
            string lc_i;
            for (i = 1; i < daysinmonth + 1; i++)
            {
                lc_i = i.ToString();
                if (lc_i.Length == 1)
                {
                    lc_i = "0" + lc_i;
                }
                isSelected = checkselected(i, sel_day);
                s.Append("<option value=" + i.ToString() + isSelected + ">" + lc_i + "</option>\n");
            }
            s.Append("</select>\n");
 
            //Build Year Dropdown
            s.Append("\n<select name=\"" + cid + "_year\"" + onchg + ostyle + ">\n");
            for (i = begyear; i <= endyear; i++)
            {
                lc_i = i.ToString();
                isSelected = checkselected(i, sel_year);
                s.Append("<option value=" + i.ToString() + isSelected + ">" + i.ToString() + "</option>\n");
            }
            s.Append("</select>\n");
 
            //Build hidden input type to hold current date
            s.Append("\n<input type=hidden name=\"" + cid + "\">\n");
            s.Append("\n<input type=hidden name=\"" + cid + "_conv\">\n");
 
            //Close container for applied styles
            if (c_ostyle != "")
            {
                s.Append("</div>");
            }
 
            //Add in object initialization for Netscape inline script bug
            s.Append(objinit);
 
            //Render control
            output.Write(s.ToString());
        }
 
        protected string checkselected(int current_selection, int compair_selection)
        {
            if (current_selection == compair_selection)
            {
                return " SELECTED";
            }
            return "";
        }
 
        //		protected void Write_Client_Scripts()
        /// <summary> 
        ///    Add date validation JavaScript to the Page 
        /// </summary> 
        /// <param name="e"></param> 
        override protected void OnPreRender(EventArgs e)
        {
            StringBuilder s = new StringBuilder();
            s.Append("\n<SCRIPT LANGUAGE=javascript>\n");
            s.Append("function tg_mm_daysinmonth(lnMonth,lnYear) {\n");
            s.Append("var dt1, cmn1, cmn2, dtt, lflag, dycnt, lmn\n");
            s.Append("lmn = lnMonth-1\n");
            s.Append("dt1 = new Date(lnYear,lmn,1)\n");
            s.Append("cmn1 = dt1.getMonth()\n");
            s.Append("dtt=dt1.getTime()+2332800000\n");
            s.Append("lflag = true\n");
            s.Append("dycnt=28\n");
            s.Append("while (lflag) {\n");
            s.Append("   dtt = dtt + 86400000\n");
            s.Append("   dt1.setTime(dtt)\n");
            s.Append("   cmn2 = dt1.getMonth()\n");
            s.Append("   if (cmn1!=cmn2) {\n");
            s.Append("      lflag = false }\n");
            s.Append("   else {dycnt = dycnt + 1}}\n");
            s.Append("if (dycnt > 31) {dycnt = 31}\n");
            s.Append("return dycnt\n");
            s.Append("}\n");
            s.Append("\n");
            s.Append("function tg_mm_setdays(sobjname, datemode){\n");
            s.Append("var dobj = eval(sobjname + \"_day\")\n");
            s.Append("var mobj = eval(sobjname + \"_month\")\n");
            s.Append("var yobj = eval(sobjname + \"_year\")\n");
            s.Append("var hobj = eval(sobjname)\n");
            s.Append("var hobjconv = eval(sobjname + \"_conv\")\n");
            s.Append("var monthdays = tg_mm_daysinmonth(mobj.options[mobj.selectedIndex].value,yobj.options[yobj.selectedIndex].value)\n");
            s.Append("var selectdays = dobj.length\n");
            s.Append("var curdy = dobj.options[dobj.selectedIndex].value\n");
            s.Append("if (curdy.length==1) {curdy = \"0\"+curdy}\n");
            s.Append("var curmn = mobj.options[mobj.selectedIndex].value\n");
            s.Append("if (curmn.length==1) {curmn = \"0\"+curmn}\n");
            s.Append("var curyr = yobj.options[yobj.selectedIndex].value\n");
            s.Append("if (selectdays > monthdays) {\n");
            s.Append("   for (var dlp=selectdays; dlp > monthdays; dlp--) {\n");
            s.Append("       dobj.options[dlp-1] = null }}\n");
            s.Append("else if (monthdays > selectdays) {\n");
            s.Append("   for (var dlp=selectdays; dlp < monthdays; dlp++) {\n");
            s.Append("       dobj.options[dlp] = new Option(dlp+1,dlp+1) }}\n");
            s.Append("if (curdy > monthdays) {\n");
            s.Append("   dobj.options[monthdays-1].selected = true\n");
            s.Append("   curdy = monthdays }\n");
            s.Append("var curdateconv = curmn+\"/\"+curdy+\"/\"+curyr\n");
            s.Append("if (datemode==1) {\n");
            s.Append("   var curdate = curmn+\"/\"+curdy+\"/\"+curyr }\n");
            s.Append("else if (datemode==2) {\n");
            s.Append("   var curdate = curdy+\"/\"+curmn+\"/\"+curyr }\n");
            s.Append("else if (datemode==3) {\n");
            s.Append("   var curdate = curyr+curmn+curdy }\n");
            s.Append("else if (datemode==4) {\n");
            s.Append("   var cdate = new Date(curyr,curmn-1,curdy)\n");
            s.Append("   var curdate = cdate.toGMTString() }\n");
            s.Append("hobj.value = curdate\n");
            s.Append("hobjconv.value = curdateconv\n");
            s.Append("}\n");
            s.Append("</SCRIPT>\n");
            s.Append("\n");
 
            // Add the Script to the Page 
            this.Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "mm_datepicker", s.ToString());
          
        }
 
    }
}

Open in new window

0
mathieu_cupryk
Asked:
mathieu_cupryk
  • 4
  • 3
1 Solution
 
Göran AnderssonCommented:
Don't just post an error message and some code, you should write something about what it is that you are trying to do, what's happening, and if you have tried something to find out what the problem is.

From what I can see from the error message, you are trying to do exact opposite of what your subject is saying, i.e. converting a string to a DateTime.

From what I can see in the client script, it's generating a date in the format MM/dd/yyyy, is that the format that your server is set up to use?

Have you tried using the DateTime.ParseExact method and specifying the format of the date?
0
 
mathieu_cuprykAuthor Commented:
green it is a weird thing it is happening in the webconfig.
0
 
Göran AnderssonCommented:
What do you mean? The error message that you posted doesn't occur in the web.config.
0
Cloud Class® Course: Python 3 Fundamentals

This course will teach participants about installing and configuring Python, syntax, importing, statements, types, strings, booleans, files, lists, tuples, comprehensions, functions, and classes.

 
mathieu_cuprykAuthor Commented:
it would seems to be happening in the control.
Line 83
  date_picked = System.DateTime.Parse(sel_date_convert).Date;
           
0
 
Göran AnderssonCommented:
Yes, that was what I was talking about in my first post. Please review.
0
 
mathieu_cuprykAuthor Commented:
I am not sure how to convert this date_picked = System.DateTime.Parse(sel_date_convert).Date;
with DateTime.ParseExact. This is my question.
0
 
mathieu_cuprykAuthor Commented:
Green are u there?
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.

Join & Write a Comment

Featured Post

Cloud Class® Course: MCSA MCSE Windows Server 2012

This course teaches how to install and configure Windows Server 2012 R2.  It is the first step on your path to becoming a Microsoft Certified Solutions Expert (MCSE).

  • 4
  • 3
Tackle projects and never again get stuck behind a technical roadblock.
Join Now