简体   繁体   中英

How to Convert date into dd.MM.yyyy format in C# from excel

In excel sheet i have date in format dd.MM.yyyy 16.10.2011 (16 as dd, 10 as MM) . When i'm importing data from excel to SQL Server 2008 i get MM.dd.yyyy but still 16.10.2011 (16 as MM, 10 as dd) . That's not correct. I found solution on this: go to SQL Server 2008 -> Security -> logins -> {user properties} -> and change default language for user. With this solution i get in SQL Server 2008 dd.MM.yyyy 16.10.2011 (16 as dd, 10 as MM) . Is there any other way to convert date in dd.MM.yyyy format without changing user language?

String sConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=c:\\JantarV7Export.xlsx;Extended Properties=Excel 8.0";
OleDbConnection olecon = new OleDbConnection(sConnectionString);

olecon.Open();
OleDbCommand cmd = olecon.CreateCommand();
cmd.CommandText = "SELECT person_id, date_of_hours, number_of_hours FROM [Sheet1$]";                    
OleDbDataAdapter oda = new OleDbDataAdapter(cmd);
OleDbDataReader odr = cmd.ExecuteReader();
conn.Open();
while (odr.Read())
{
    SqlCommand cmd1 = conn.CreateCommand();

    cmd1.CommandText = "INSERT INTO test_data values (newid(),'" + odr[0] + "',@date_of_hours,'" + odr[2] + "')";
    cmd1.Parameters.Add("@date_of_hours", SqlDbType.DateTime).Value =odr[1];
}
cmd1.ExecuteNonQuery();
olecon.Close();
conn.Close();

I think that problem is when i'm inserting into test_data datatable. So i probably should convert dates somehow before inserting. What do you suggest? Thanks. Is there any options like this:

cmd1.CommandText = "INSERT INTO test_data values (newid(),'" + odr[0] + 
    "',CONVERT(VARCHAR(20),@date_of_hours,104),'" + odr[2] + "')";
cmd1.Parameters.Add("@date_of_hours", SqlDbType.DateTime).Value =odr[1];

(this doesn't work because of CONVERT in insert, but is there some similar solution) or

CONVERT(VARCHAR(20),@date_of_hours,104) AS [DD:MM:YYYY]

UPDATE In other form i read data through combobox. It shows 1.10.2011, 2.10.2011, .... to 16.10.2011.

da_test_data = new SqlDataAdapter("SELECT test_data_id, date_of_hours, number_of_hours FROM test_data WHERE _person_id= '" + person_id_person + "' ORDER BY date_of_hours", conn);
dt_test_data = new DataTable();
da_test_data.Fill(dt_test_data);
cb_datum.DataSource = dt_test_data.DefaultView;
cb_datum.ValueMember = "test_data_id";
cb_datum.DisplayMember = "date_of_hours";

And combobox for projects :

 private void cb_datum_SelectedIndexChanged(object sender, EventArgs e)
 {
      DataRowView drvProjekt = cb_datum.SelectedItem as DataRowView;
      if (drvProjekt != null)
      {
          string date1 = drvProjekt["date_of_hours"].ToString();  
          DateTime date2 = new DateTime();
          date2 =Convert.ToDateTime(date1);

          //DateTime date = DateTime.ParseExact(date1, "MMddyyyy hh:mm:ss", null);
          //DateTime date = DateTime.ParseExact(date1, "dd.MM.yyyy", System.Globalization.CultureInfo.CurrentUICulture.DateTimeFormat);

          //object obj = DateTime.ParseExact(dddd, "MM/dd/yyyy hh:mm", null);
          conn = new SqlConnection(connectionString);
          conn.Open();

          da_projekt = new SqlDataAdapter("SELECT projekt_id, name_of_projekt, date_of_start, date_of_end FROM projekt WHERE date_of_start < '" + date2 + "' AND date_of_end > '" + date2 + "' ", conn);
          dt_projekt = new DataTable();
          da_projekt.Fill(dt_projekt);
          cb_projekt_id.DataSource = dt_projekt.DefaultView;
          cb_projekt_id.ValueMember = "projekt_id";
          cb_projekt_id.DisplayMember = "name_of_projekt";
          conn.Close();
      }
 }

When i select 13.10.2011 i get error. Date is recognised as MM.dd.yyyy. I tried everything (all in comments and many more). Yust don't find a solution.

As I mentioned in the comment. your date value is stored as Date in SQL. So when you store date in SQL it will remain date only, and when you retrieve it you will get date object directly. In SQL, it might be displayed as MM.dd.yyyy it doesn't matter.

When you will read this data from SQL, you will get DateTime object, on this if you do .ToString("dd.MM.yyyy", CultureInfo.InvariantCulture) you will get in dd.MM.yyyy format. You can use any format on DateTime object, read more about it on MSDN .

Hope this answers your question.

If possible, just replace "." with "/" in the excel file and format the cell as dd/mmm/yyyy

Excel natively keeps dates as days since some date I do not remember as a floating point value. The important thing is that this matches DateTime.ToOADate().

We read dates from excel files as a floating point value and then use DateTime.ToOADate().

You use CONVERT the wrong way. Database-side, you convert a datetime to a string (varchar), and then you have to rely on build-in type conversions to get a datetime again. You should do it the other way around. If in c# you convert the datetime to a string with a specified format and convert it to a datetime with a matching style database-side nothing can go wrong.

When you use CONVERT the date part should match the style you use (in your case 104). Use this in your sql:

CONVERT(DATETIME, @date_of_hours, 104)

and

cmd1.Parameters.Add("@date_of_hours", SqlDbType.NVarChar).Value =
    string.Format("{0:dd.MM.yyyy}", odr[1])

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