简体   繁体   中英

Convert date format on fly in asp.net c#

i am uploading an excel file which has a date column having this format "dd-mm-yyyy". I am trying to convert it on fly into this format mm/dd/yyyy.

string[] dsplit = row[6].ToString().Split('-');
obj.ExpiryDate = string.Format("{0}/{1}/{2}", dsplit[1], dsplit[0], dsplit[2]).ToDate();

but it throws error, some hidden error.

Here is the whole code. I have tried a alot and nothing works expectedly

protected void SaveEmployeefrom_Click(object sender, EventArgs e)
    {
        uploadExcelfile();
    }
    public List<ClsEmployee> uploadExcelfile()
    {
        List<ClsEmployee> list = new List<ClsEmployee>();
        DataTable tb = new DataTable();
        try
        {

            if (employeeregistration.HasFile)
            {

                string name = DateTime.Now.ToString("hhmmss_ddmmyy");
                name = name + employeeregistration.FileName;

                employeeregistration.SaveAs(Server.MapPath("~/ExcelFiles/") + name);

                string path = System.IO.Path.GetFullPath(Server.MapPath("~/ExcelFiles/") + name);
                string connString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + path + ";Extended Properties=\"Excel 12.0;HDR=Yes;IMEX=2\"";
                if (Path.GetExtension(path) == ".xls")
                {
                    excelconnection = new OleDbConnection(connString);
                    excelconnection.Open();
                }
                else if (Path.GetExtension(path) == ".xlsx")
                {
                    excelconnection = new OleDbConnection(connString);
                    excelconnection.Open();

                }
                OleDbCommand cmd = new OleDbCommand("SELECT [Name],[ID],[Mobile No],[Phone],[Emirates],[Nationality],[ExpiryDate],[Address] FROM [sheet1$]", excelconnection);
                OleDbDataAdapter oleda = new OleDbDataAdapter(cmd);

                oleda.Fill(tb);
                foreach (DataRow row in tb.Rows)
                {
                    if (!string.IsNullOrEmpty(row[6].ToString()))
                    {
                        ClsEmployee obj = new ClsEmployee();
                        obj.ID = 0;
                        // obj.Employer_ID=row[0].ToInt32();
                        obj.EmployeeName = row[0].ToString();
                        obj.EmployeeUniqueID = row[1].ToString();
                        obj.MobileNumber = row[2].ToString();
                        obj.PhoneNumber = row[3].ToString();
                        obj.Emirates = row[4].ToString();
                        obj.Nationality = row[5].ToString();
                        //from excel its dd-mm-yyyy
                        string[] dsplit = row[6].ToString().Split('-');
                        obj.ExpiryDate = string.Format("{0}/{1}/{2}", dsplit[1], dsplit[0], dsplit[2]).ToDate();
                       // obj.ExpiryDate = row[6].ToDate(); //mm-dd-yyyy
                        obj.Address = row[7].ToString();
                        list.Add(obj); 
                    }

                }
                excelconnection.Dispose();
                if (File.Exists(path))
                {
                    File.Delete(path);
                }
                int total = tb.Rows.Count;
                if (total>0)
                {
                    GV_Employee.DataSource = null;
                    GV_Employee.DataSource = list;
                    GV_Employee.DataBind();
                    GV_Employee.Visible = true;
                    ResultLabel.ResultLabelAttributes("Uploaded successfull !!!", ProjectUserControls.Enums.ResultLabel_Color.Yellow);
                    ResultPanel.Controls.Add(ResultLabel);
                }
                else
                {
                    ResultLabel.ResultLabelAttributes("No Record In Excel Sheet !!!", ProjectUserControls.Enums.ResultLabel_Color.Red);
                    ResultPanel.Controls.Add(ResultLabel);
                }
               //txtSerialQuantity.Text = total.ToString();

                ////// trbtnCheckAll.Visible = true;
                ////div_automatic.Visible = true;
                ////lbl_totalSelected.Text = "Total Selected = " + total.ToString();

            }
        }
        catch (Exception x)
        {
            x.ToString(); //ResultLabel.ResultLabelAttributes(x.Message, ProjectUserControls.Enums.ResultLabel_Color.Red);
            ResultLabel.ResultLabelAttributes(x.Message, ProjectUserControls.Enums.ResultLabel_Color.Red);
            ResultPanel.Controls.Add(ResultLabel);
        }
        return list;
    }
    protected void Button1_Click(object sender, EventArgs e)
    {
        ClsEmployee obj1 = new ClsEmployee();
        List<ClsEmployee> list = new List<ClsEmployee>();
        try
        {
            foreach (GridViewRow item in GV_Employee.Rows)
            {
                ClsEmployee obj = new ClsEmployee();
                obj.ID = 0;
                obj.Employer_ID = cmbEmployer.SelectedValue.ToInt32();// ((Literal)GV_Employee.Rows[1].FindControl("Ltrl_EmployerID")).Text.ToInt32();
                obj.EmployeeName = ((Literal)item.FindControl("Ltrl_Name")).Text.ToString();
                obj.EmployeeUniqueID = ((Literal)item.FindControl("Ltrl_EmployeeUniqueID")).Text.ToString();
                obj.MobileNumber = ((Literal)item.FindControl("Ltrl_Mobile")).Text.ToString();
                obj.PhoneNumber = ((Literal)item.FindControl("Ltrl_PhoneNo")).Text.ToString();
                obj.Emirates_ID = ((Literal)GV_Employee.Rows[1].FindControl("Ltrl_Emirates")).Text.ToInt32();
                obj.Nationality_ID = ((Literal)GV_Employee.Rows[1].FindControl("Ltrl_Nationality")).Text.ToInt32();
                obj.ExpiryDate = ((Literal)item.FindControl("Ltrl_Expiry")).Text.ToDate();
                obj.Address = ((Literal)item.FindControl("Ltrl_Address")).Text.ToString();
                obj.LFMD = "";
                obj.RFMD = "";
                obj.PinCode = "";
                obj.IsFingerAuth = false;
                obj.IsActive = true;
                list.Add(obj);

            }
            obj1.SaveEmployeefromExcelFile(list);
            ResultLabel.ResultLabelAttributes("Save successfull !!!", ProjectUserControls.Enums.ResultLabel_Color.Yellow);
            ResultPanel.Controls.Add(ResultLabel);
            GV_Employee.DataSource = null;
            GV_Employee.Visible = false;
        }
        catch (Exception ex)
        {

            ResultLabel.ResultLabelAttributes(ex.ToString(), ProjectUserControls.Enums.ResultLabel_Color.Red);
            ResultPanel.Controls.Add(ResultLabel);
        }

    }

Try this code.

DateTime dt = DateTime.Parse(row[6].toString());
string date = dt.ToString("dd/MM/yyyy");

I assume row[6] is a DateTime when you get from excel, you just need;

row[6].ToString("MM/dd/yyyy", CultureInfo.InvariantCulture);

Convert a DateTime to string and splitting it a generally bad idea. mm specifier is for minutes, MM is for months by the way.

Try This..

 String MyString = "12-30-2014"; // get value from text field
        DateTime MyDateTime = new DateTime();
        MyDateTime = DateTime.ParseExact(MyString, "MM-dd-yyyy",null);
        String MyString_new = MyDateTime.ToString("dd-MM-yyyy"); 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM