2013-09-21 29 views
1

我想只保存到数据库的“时间”。节省时间到数据库也跟着日期

但是,我所得到的是“时间”,其次是“DATE”

这里是我的数据库程序中的截图后,我把它添加到数据库文件:

enter image description here

如果您在“时间”列中看到日期后的时间。我不想那么做(我只想要显示在“时代”专栏中的时间)。

此外,我已经在数据库文件中设置“Times”的格式为“Medium Time”,这会给我“4:56 PM”。

这里是在数据库中的时间截图:

enter image description here

数据库文件的时间是正确的,因为它仅显示时间。但是,在我使用datagridview显示数据库的程序中,它显示了日期之后的时间。

我如何改变它,让我只能看到时间?

下面是代码:

private void AddDatabase(object sender, EventArgs e) 
    { 
     using (OleDbConnection conn = new OleDbConnection(connectionString)) 
     { 
      string query = "INSERT INTO [Record] ([Times]) VALUES (@Times)"; 

      conn.Open(); 

      using (OleDbCommand cmd = new OleDbCommand(query, conn)) 
      { 
        _cmd.Parameters.Add("@Times", System.Data.OleDb.OleDbType.DBTimeStamp); 
        _cmd.Parameters["@Times"].Value = DateTime.Now.ToShortTimeString(); 

        int _numberOfRows = _cmd.ExecuteNonQuery(); 
       } 

       if (_choice.comboBox1.Text == "English") 
       { 
        System.Media.SoundPlayer _sound = new System.Media.SoundPlayer(@"C:\Windows\Media\Windows Exclamation.wav"); 
        _sound.Play(); 

        DialogResult _dialogResult = MessageBox.Show("Added Successfully!", "Success", MessageBoxButtons.OK); 

        if (_dialogResult == DialogResult.OK) 
        { 
         ViewDatabase(sender, e); 

         ClearTextBoxes(sender, e); 
        } 
       } 
      } 

      conn.Close(); 
     } 
    } 

基本上,我如何使用“格式”中的数据库文件到代码?

回答

0

您可以根据需要使用DateTime.ToString(formatString)方法格式化日期时间。 然后你可以显示数据网格或任何你想要的结果字符串。

var dtTime =(DateTime) dataReader["Times"]; 
var strTime = datTime.ToString("hh:mm tt"); 
+0

显示假设你是从数据库中使用的DataReader – VahiD

+0

读取行我是否需要在'[“Times”]后面加上'='后面的值?先生?而且,我应该怎么处理'datTime'?不应该是这样的:'var dtTime =(DateTime)dataReader [“Times”]; var strTime = dtTime.ToString(“hh:mm tt”);'而不是你写的。 – Kaoru

+0

我写的代码只是为了显示存储时间,只是格式化显示。我以为你有正确的格式显示问题 – VahiD

0
2008+拥有 TIME数据类型

SQL SERVER,你可以用它来存储时间,你可以看看这个article在.NET应用程序中使用它,只是一个提示,你可以用时间跨度的数据键入净

+2

谢谢。但我现在正在使用ACCESS,而不是SQL。 – Kaoru

+0

所以最好的解决方案是将时间存储为从午夜开始的秒数(或毫秒)(例如3735表示01:02:15),然后使用.Net – VahiD

+0

中的广告时间段数据类型,可以给我一个例子,瓦希德?谢谢 – Kaoru

0

您可以将时间存储为从午夜秒数,例如你的情况:

你定义时报数据库INT申请,并

_cmd.Parameters.Add("@Times", System.Data.OleDb.OleDbType.Integer); 
_cmd.Parameters["@Times"].Value = (int)DateTime.Now.TimeOfDay.TotalSeconds; 

,并从数据库中读取后,你可以的秒数转换为时间

int soconds = reader["Times"]; 
string time = string.Format("{0:00}:{1:00}:{2:00}",seconds/3600,seconds/60,seconds%60); 

时间是你想要的格式文本中或网格等

+1

没有DateTime.TimeOfDay先生。 – Kaoru

+0

对不起DateTime.Now.TimeOfDay – VahiD