2011-04-11 86 views
23

我使用這種格式的數據讀取器讀取一個字符串。我如何使用類似的格式閱讀日期?使用DataReader讀取日期

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

什麼是日期列的SQL **數據類型**? – abatishchev 2011-04-11 09:38:45

回答

31

嘗試,如下所示:

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

ToString()方法可以更改數據格式按您的要求。

+0

ConvertTo錯誤。在當前情況下不存在。 – TeaDrinkingGeek 2011-04-11 09:29:46

+0

plz現在查看更新後的問題。 – Sukhjeevan 2011-04-11 09:37:00

+0

它的工作原理。謝謝。 – TeaDrinkingGeek 2011-04-11 09:46:15

5
(DateTime)MyReader["ColumnName"]; 

OR

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

(DateTime)MyReader [「Date」];給出錯誤 – TeaDrinkingGeek 2011-04-11 09:31:51

+0

您是否嘗試過這一個Convert.ToDateTime(MyReader [「ColumnName」]); ? – 2011-04-11 09:40:52

+0

這兩個表達式都返回DateTime。同時左表達式接受'String'。所以你需要調用'ToString()'。 – abatishchev 2011-04-11 09:48:58

9

如果如果查詢的專欄實際上是一個字符串,然後看其他的答案查詢的列有一個合適的類型,然後

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

+0

GetDateTime只接受一個整數:http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqldatareader.getdatetime%28v=vs。 110%29.aspx – sikander 2014-02-23 04:33:11

+0

@sikander我只能聲稱我忘記使用'GetOrdinal'。 – Richard 2014-02-23 10:05:21

+0

MS不允許列名是愚蠢的。歡呼更新你的答案。 – sikander 2014-02-24 02:43:17

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

這似乎稍微偏離主題,但這個不知道,當你讀一列在C#中的日期時間會發生什麼,當我遇到了職。這篇文章反映了我希望能夠找到關於這種機制的信息。 如果擔心UTC和時區,然後在

讀我一樣,我是因爲它對你使用的是什麼時區自動假設,因爲總是非常謹慎的日期時間爲一類多一點研究它的方式太容易混淆當地時間和時代。

我在這裏試圖避免的是DateTime去'哦,看看我正在運行的計算機是在時區x,因此這次也必須在時區x,當我被問到我的價值觀我'會回覆,就好像我在那個時區'

我正在嘗試閱讀datetime2列。

你將從sql服務器得到的日期時間將最終爲Kind.Unspecified這似乎意味着它被視爲UTC,這正是我想要的。

當閱讀date列時,即使沒有時間並且更容易被時區擰得太緊(因爲它在午夜時分),您也必須將其作爲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在顯示它們之前不會將時間轉換爲本地時間。這是一種解脫!

+1

你可以像'DateTime.SpecifyKind(reader.GetDateTime(1),DateTimeKind.Utc'''縮短這個,所以你不必手動玩弄滴答:) – jocull 2017-01-17 16:55:53

0

在我的情況下,我將SQL數據庫中的日期時間字段更改爲不允許爲空。 SqlDataReader然後允許我直接將值轉換爲DateTime。

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