使用DataReader读取日期

时间:2011-04-11 09:22:18

标签: c# .net ado.net datareader

我使用数据读取器使用此格式读取字符串。如何使用类似的格式阅读日期?

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

8 个答案:

答案 0 :(得分:35)

尝试如下:

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

ToString()方法中,您可以根据自己的要求更改数据格式。

答案 1 :(得分:12)

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

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

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

答案 2 :(得分:7)

 (DateTime)MyReader["ColumnName"];

OR

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

答案 3 :(得分:7)

这可能看起来略显偏离主题,但这是我想知道当你在c#中读取一个列作为dateTime时会发生什么的帖子。该帖子反映了我希望能够找到关于这种机制的信息。 如果您担心utc和时区,请继续阅读

我做了一些研究,因为我总是非常警惕DateTime作为一个班级,因为它自动假设你正在使用什么时区,因为太容易混淆当地时间和utc时间。

我在这里要避免的是DateTime要去'看看我正在运行的计算机是在时区x,所以这次也必须在时区x,当我被问到我的价值观我会回复,好像我在那个时区'

我试图阅读datetime2列。

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

在阅读date列时,您还必须将其读作DateTime,即使它没有时间,也更容易被时区搞砸(因为它是在午夜)。< / p>

我当然认为这是读取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

查看TimeZoneInfo.GetSystemTimeZones();提供的列表

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

答案 4 :(得分:0)

        /// <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
        };
    }

OR

        /// <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 :(得分:0)

在我的情况下,我将SQL数据库中的datetime字段更改为不允许null。然后SqlDataReader允许我将值直接转换为DateTime。

答案 6 :(得分:0)

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

  

DateTime对象的形式获取指定列的值。

您可以使用:

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

答案 7 :(得分:-1)

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();
        }
    }
}