使用DataReader读取日期

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

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

尝试如下:

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

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

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

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

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

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

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

我在这里要避免的是DateTime ‘哦,看看我正在运行的计算机是在时区x,因此这个时间也必须在时区x,当我被问到我的值时,我会回复,就像我在那个时区’

我试图读取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可能不是你想要的那样 – 因为你在客户端上乱搞,你可能需要先将它转换为当地时间(取决于时间的含义是什么) )。 然而,这开辟了一大堆蠕虫..如果你需要这样做,我建议使用像诺达时间这样的库。 标准库中有TimeZoneInfo ,但在对其进行简要调查后,它似乎没有一组合适的时区 。 您可以使用TimeZoneInfo.GetSystemTimeZones();方法查看TimeZoneInfo提供的列表TimeZoneInfo.GetSystemTimeZones();

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

  (DateTime)MyReader["ColumnName"]; 

要么

 Convert.ToDateTime(MyReader["ColumnName"]); 
  ///  /// Returns a new conContractorEntity instance filled with the DataReader's current record data ///  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 }; } 

要么

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

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

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

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

您可以使用如下:

 while (MyReader.Read()) { TextBox1.Text = MyReader.GetDateTime(columnPosition).ToString("dd/MM/yyyy"); } 
 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(); } } }