【问题标题】:Reading a date using DataReader使用 DataReader 读取日期
【发布时间】:2011-08-02 22:00:09
【问题描述】:

我通过数据阅读器使用这种格式读取了一个字符串。如何使用类似格式读取日期?

while (MyReader.Read())
{
    TextBox1.Text = (string)MyReader["Note"];
}

【问题讨论】:

  • 日期列的SQL 数据类型是什么?

标签: c# .net ado.net datareader


【解决方案1】:

尝试如下:

while (MyReader.Read())
{
    TextBox1.Text = Convert.ToDateTime(MyReader["DateField"]).ToString("dd/MM/yyyy");
}

ToString() 方法中,您可以根据需要更改数据格式。

【讨论】:

    【解决方案2】:
     (DateTime)MyReader["ColumnName"];
    

    Convert.ToDateTime(MyReader["ColumnName"]);
    

    【讨论】:

    • 你试过这个吗 Convert.ToDateTime(MyReader["ColumnName"]); ?
    • 右表达式都返回DateTime。同时左表达式接受String。所以无论如何你都需要打电话给ToString()
    • @abatishchev;是的,这很明显,我刚刚为他提供了如何转换为 DateTime 的解决方案。我忽略了那部分,因为我假设,他一定知道这件事
    • 对。然后只需删除左侧部分以使代码可编译:)
    【解决方案3】:

    如果查询的列具有适当的类型,则

    var dateString = MyReader.GetDateTime(MyReader.GetOrdinal("column")).ToString(myDateFormat)
    

    如果查询的列实际上是一个字符串,那么请查看其他答案。

    【讨论】:

    • GetDateTime 只接受整数:msdn.microsoft.com/en-us/library/…
    • @sikander 我只能声称我始终如一地忘记使用GetOrdinal
    • MS 不允许列名是愚蠢的。为更新您的答案干杯。
    【解决方案4】:
            /// <summary>
        /// Returns a new conContractorEntity instance filled with the DataReader's current record data
        /// </summary>
        protected virtual conContractorEntity GetContractorFromReader(IDataReader reader)
        {
            return new conContractorEntity()
            {
                ConId = reader["conId"].ToString().Length > 0 ? int.Parse(reader["conId"].ToString()) : 0,
                ConEmail = reader["conEmail"].ToString(),
                ConCopyAdr = reader["conCopyAdr"].ToString().Length > 0 ? bool.Parse(reader["conCopyAdr"].ToString()) : true,
                ConCreateTime = reader["conCreateTime"].ToString().Length > 0 ? DateTime.Parse(reader["conCreateTime"].ToString()) : DateTime.MinValue
            };
        }
    

            /// <summary>
        /// Returns a new conContractorEntity instance filled with the DataReader's current record data
        /// </summary>
        protected virtual conContractorEntity GetContractorFromReader(IDataReader reader)
        {
            return new conContractorEntity()
            {
                ConId = GetValue<int>(reader["conId"]),
                ConEmail = reader["conEmail"].ToString(),
                ConCopyAdr = GetValue<bool>(reader["conCopyAdr"], true),
                ConCreateTime = GetValue<DateTime>(reader["conCreateTime"])
            };
        }
    
    // Base methods
            protected T GetValue<T>(object obj)
        {
            if (typeof(DBNull) != obj.GetType())
            {
                return (T)Convert.ChangeType(obj, typeof(T));
            }
            return default(T);
        }
    
        protected T GetValue<T>(object obj, object defaultValue)
        {
            if (typeof(DBNull) != obj.GetType())
            {
                return (T)Convert.ChangeType(obj, typeof(T));
            }
            return (T)defaultValue;
        }
    

    【讨论】:

      【解决方案5】:

      这似乎有点偏离主题,但这是我在想知道当您在 c# 中将列作为 dateTime 读取时会发生什么时遇到的帖子。该帖子反映了我希望能够找到的有关此机制的信息。 如果您担心 UTC 和时区,请继续阅读

      我做了更多的研究,因为我总是对 DateTime 作为一个类非常警惕,因为它会自动假设您使用的是哪个时区,而且很容易混淆当地时间和 UTC 时间。

      我在这里要避免的是 DateTime 去我会像在那个时区一样回复'

      我试图阅读datetime2 专栏。

      您将从 sql server 返回的日期时间最终将是 Kind.Unspecified 这似乎意味着它被视为 UTC,这正是我想要的。

      读取date 列时,您还必须将其读取为DateTime,即使它没有时间并且更容易被时区搞砸(因为它是在午夜)。

      我当然认为这是读取 DateTime 的更安全的方式,因为我怀疑它可能会被 sql server 中的设置或 c# 中的静态设置修改:

      var time = reader.GetDateTime(1);
      var utcTime = new DateTime(time.Ticks, DateTimeKind.Utc);
      

      您可以从那里获取组件(日、月、年)等,并按照您的喜好设置格式。

      如果您实际上是一个日期 + 一个时间,那么 Utc 可能不是您想要的 - 因为您在客户端上乱搞,您可能需要先将其转换为本地时间(取决于现在的时间是)。然而,这会打开一大堆蠕虫。如果你需要这样做,我建议使用像 noda time 这样的库。标准库中有TimeZoneInfo,但经过简单调查后,似乎没有proper set of timezones。使用TimeZoneInfo.GetSystemTimeZones();方法可以看到TimeZoneInfo提供的列表

      我还发现 sql server management studio 在显示时间之前不会将时间转换为本地时间。这是一种解脱!

      【讨论】:

      • 你可以像DateTime.SpecifyKind(reader.GetDateTime(1), DateTimeKind.Utc)这样缩短它,这样你就不必手动处理刻度了:)
      【解决方案6】:

      在我的例子中,我将 SQL 数据库中的日期时间字段更改为不允许为空。然后 SqlDataReader 允许我将值直接转换为 DateTime。

      【讨论】:

        【解决方案7】:
        using System;
        using System.Collections.Generic;
        using System.ComponentModel;
        using System.Data;
        using System.Drawing;
        using System.Linq;
        using System.Text;
        using System.Threading.Tasks;
        using System.Windows.Forms;
        using System.Data.SqlClient;
        namespace Library
        {
            public partial class Form1 : Form
            {
                public Form1()
                {
                    InitializeComponent();
                }
        
                private void Form1_Load(object sender, EventArgs e)
                {
        
                }
        
                private void textBox1_TextChanged(object sender, EventArgs e)
                {
        
                }
        
                private void button1_Click(object sender, EventArgs e)
                {
                    SqlConnection con = new SqlConnection(@"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=C:\Users\NIKHIL R\Documents\Library.mdf;Integrated Security=True;Connect Timeout=30");
                    string query = "INSERT INTO [Table] (BookName , AuthorName , Category) VALUES('" + textBox1.Text.ToString() + "' , '" + textBox2.Text.ToString() + "' , '" + textBox3.Text.ToString() + "')";
                    SqlCommand com = new SqlCommand(query, con);
                    con.Open();
                    com.ExecuteNonQuery();
                    con.Close();
                    MessageBox.Show("Entry Added");
                }
        
                private void button3_Click(object sender, EventArgs e)
                {
                    SqlConnection con = new SqlConnection(@"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=C:\Users\NIKHIL R\Documents\Library.mdf;Integrated Security=True;Connect Timeout=30");
                    string query = "SELECT * FROM [TABLE] WHERE BookName='" + textBox1.Text.ToString() + "' OR AuthorName='" + textBox2.Text.ToString() + "'";
                    string query1 = "SELECT BookStatus FROM [Table] where BookName='" + textBox1.Text.ToString() + "'";
                    string query2 = "SELECT DateOfReturn FROM [Table] where BookName='" + textBox1.Text.ToString() + "'";
                    SqlCommand com = new SqlCommand(query, con);
                    SqlDataReader dr, dr1,dr2;
                    con.Open();
                    com.ExecuteNonQuery();
                    dr = com.ExecuteReader();
        
                    if (dr.Read())
                    {
                        con.Close();
                        con.Open();
                        SqlCommand com1 = new SqlCommand(query1, con);
                        com1.ExecuteNonQuery();
                        dr1 = com1.ExecuteReader();
                        dr1.Read();
                        string i = dr1["BookStatus"].ToString();
                        if (i =="1" )
                        {
                            con.Close();
                            con.Open();
                            SqlCommand com2 = new SqlCommand(query2, con);
                            com2.ExecuteNonQuery();
                            dr2 = com2.ExecuteReader();
                            dr2.Read();
        
        
                                MessageBox.Show("This book is already issued\n " + "Book will be available by "+ dr2["DateOfReturn"] );
        
                        }
                        else
                        {
                            con.Close();
                            con.Open();
                            dr = com.ExecuteReader();
                            dr.Read();
                           MessageBox.Show("BookFound\n" + "BookName=" + dr["BookName"] + "\n AuthorName=" + dr["AuthorName"]);
                        }
                        con.Close();
                    }
                    else
                    {
                        MessageBox.Show("This Book is not available in the library");
                    }
                }
        
                private void button2_Click(object sender, EventArgs e)
                {
                    SqlConnection con = new SqlConnection(@"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=C:\Users\NIKHIL R\Documents\Library.mdf;Integrated Security=True;Connect Timeout=30");
                    string query = "SELECT * FROM [TABLE] WHERE BookName='" + textBox1.Text.ToString() + "'";
                    string dateofissue1 = DateTime.Today.ToString("dd-MM-yyyy");
                    string dateofreturn = DateTime.Today.AddDays(15).ToString("dd-MM-yyyy");
                    string query1 = "update [Table] set BookStatus=1,DateofIssue='"+ dateofissue1 +"',DateOfReturn='"+ dateofreturn +"' where BookName='" + textBox1.Text.ToString() + "'";
                    con.Open();
                    SqlCommand com = new SqlCommand(query, con);
                    SqlDataReader dr;
                    com.ExecuteNonQuery();
                    dr = com.ExecuteReader();
                    if (dr.Read())
                    {
                        con.Close();
                        con.Open();
                        string dateofissue = DateTime.Today.ToString("dd-MM-yyyy");
                        textBox4.Text = dateofissue;
                        textBox5.Text = DateTime.Today.AddDays(15).ToString("dd-MM-yyyy");
                        SqlCommand com1 = new SqlCommand(query1, con);
                        com1.ExecuteNonQuery();
                        MessageBox.Show("Book Isuued");
                    }
                    else
                    {
                        MessageBox.Show("Book Not Found");
                    }
                    con.Close();
        
                }
        
                private void button4_Click(object sender, EventArgs e)
                {
                    SqlConnection con = new SqlConnection(@"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=C:\Users\NIKHIL R\Documents\Library.mdf;Integrated Security=True;Connect Timeout=30");
                    string query1 = "update [Table] set BookStatus=0 WHERE BookName='"+textBox1.Text.ToString()+"'";
                    con.Open();
                    SqlCommand com = new SqlCommand(query1, con);
                    com.ExecuteNonQuery();
                    string today = DateTime.Today.ToString("dd-MM-yyyy");
                    DateTime today1 = DateTime.Parse(today);
                    string query = "SELECT dateofReturn from [Table] where BookName='" + textBox1.Text.ToString() + "'";
                    con.Close();
                    con.Open();
                    SqlDataReader dr;
                    SqlCommand cmd = new SqlCommand(query, con);
                    cmd.ExecuteNonQuery();
                    dr = cmd.ExecuteReader();
                    dr.Read();
                    string DOR = dr["DateOfReturn"].ToString();
                    DateTime dor = DateTime.Parse(DOR);
                    TimeSpan ts = today1.Subtract(dor);
                    string query2 = "update [Table] set DateOfIssue=NULL, DateOfReturn=NULL WHERE BookName='" + textBox1.Text.ToString() + "'";
                    con.Close();
                    con.Open();
                    SqlCommand com2 = new SqlCommand(query2, con);
                    com2.ExecuteNonQuery();
                    int x = int.Parse(ts.Days.ToString());
                    if (x > 0)
                    {
                        int fine = x * 5;
                        textBox6.Text = fine.ToString();
                        MessageBox.Show("Book Received\nFine=" + fine);
                    }
                    else
                    {
                        textBox6.Text = "0";
                        MessageBox.Show("Book Received\nFine=0");
                    }
                        con.Close();
                }
            }
        }
        

        【讨论】:

          【解决方案8】:

          我知道这是一个老问题,但我很惊讶没有答案提到GetDateTime

          获取指定列的值作为DateTime 对象。

          你可以像这样使用:

          while (MyReader.Read())
          {
              TextBox1.Text = MyReader.GetDateTime(columnPosition).ToString("dd/MM/yyyy");
          }
          

          【讨论】:

          • 我认为接受的答案是一个很好的答案,因为从OP 的问题中可以清楚地看出:I read a string using this format with a data reader. How can I read in a date using similar format? OP 的问题是他/她有一个字符串格式的列,但想要以日期格式转换/显示它。一个例子是SQLite db,我们以字符串格式输入日期。参考:SQLite Data Types.
          猜你喜欢
          • 2011-03-18
          • 1970-01-01
          • 2018-06-05
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2018-02-25
          相关资源
          最近更新 更多