简体   繁体   English

如何在excel中将日期转换为C#中的dd.MM.yyyy格式

[英]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) . 在excel表格中,我的日期格式为dd.MM.yyyy 16.10.2011 (16为dd,10为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) . 当我从excel导入数据到SQL Server 2008时,我得到MM.dd.yyyy但仍然是16.10.2011 (16为MM,10为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. 我找到了解决方案:转到SQL Server 2008 - >安全 - >登录 - > {用户属性} - >并更改用户的默认语言。 With this solution i get in SQL Server 2008 dd.MM.yyyy 16.10.2011 (16 as dd, 10 as MM) . 有了这个解决方案,我进入SQL Server 2008 dd.MM.yyyy 16.10.2011 (16为dd,10为MM) Is there any other way to convert date in dd.MM.yyyy format without changing user language? 有没有其他方法可以在不更改用户语言的情况下以dd.MM.yyyy格式转换日期?

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. 我认为问题是当我插入test_data 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,这不起作用,但是有一些类似的解决方案)或

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. 它显示1.10.2011,2.10.2011,....至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. 当我选择13.10.2011时,我收到错误。 Date is recognised as MM.dd.yyyy. 日期被识别为MM.dd.yyyy。 I tried everything (all in comments and many more). 我尝试了一切(所有评论和更多)。 Yust don't find a solution. Yust找不到解决方案。

As I mentioned in the comment. 正如我在评论中提到的那样。 your date value is stored as Date in SQL. 您的日期值在SQL中存储为Date So when you store date in SQL it will remain date only, and when you retrieve it you will get date object directly. 因此,当您在SQL中存储日期时,它将仅保留日期,当您检索它时,您将直接获得日期对象。 In SQL, it might be displayed as MM.dd.yyyy it doesn't matter. 在SQL中,它可能显示为MM.dd.yyyy并不重要。

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. 当您从SQL中读取此数据时,您将获得DateTime对象,如果您执行.ToString("dd.MM.yyyy", CultureInfo.InvariantCulture)您将获得dd.MM.yyyy格式。 You can use any format on DateTime object, read more about it on MSDN . 您可以在DateTime对象上使用任何格式,在MSDN上阅读有关它的更多信息。

Hope this answers your question. 希望这能回答你的问题。

If possible, just replace "." 如果可能,只需替换“。” with "/" in the excel file and format the cell as dd/mmm/yyyy 在excel文件中使用“/”并将单元格格式化为dd / mmm / yyyy

Excel natively keeps dates as days since some date I do not remember as a floating point value. Excel本身将日期保留为自某个日期以来我不记得作为浮点值的日期。 The important thing is that this matches DateTime.ToOADate(). 重要的是,这匹配DateTime.ToOADate()。

We read dates from excel files as a floating point value and then use DateTime.ToOADate(). 我们从excel文件中读取日期作为浮点值,然后使用DateTime.ToOADate()。

You use CONVERT the wrong way. 你以错误的方式使用CONVERT 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. 在数据库端,您将日期时间转换为字符串(varchar),然后您必须依赖内置类型转换来再次获取日期时间。 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. 如果在c#中将datetime转换为具有指定格式的字符串,并将其转换为具有匹配样式的数据库端的日期时间,则不会出错。

When you use CONVERT the date part should match the style you use (in your case 104). 当您使用CONVERT ,日期部分应与您使用的样式匹配(在您的情况下为104)。 Use this in your sql: 在你的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])

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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