仅使用C#作为HH:mm AM / PM在SQL Server中存储时间

时间:2015-04-08 07:10:28

标签: c# sql-server-2008 datetime

如何从C#中的DateTime结构中仅将日期的时间部分插入到Sql Server中。我想以HH:mm tt(HH:MM AM / PM)

的格式保存时间

我尝试了以下数据类型:

  1. time
  2. timestamp
  3. datetime
  4. time(7)
  5. 示例查询:

    SqlCommand cmd = new SqlCommand("insert into Reminder values ('" + txttitle.Text + "','" + txtdate.Text + "','" + txttime.Text + "','" + Txtmail.Text + "')", conn);
    cmd.ExecuteNonQuery();
    

2 个答案:

答案 0 :(得分:4)

我认为你误解了一些事情......

让我们首先看看C#方面。 DateTime包含日期和时间值作为数字。 TimeSpan时间间隔。这也将这些时间值保持为数字。但是间隔词在这里很重要,因为它没有任何日期或其他内容,如DateTime。它将时间长度保持为Ticks

在SQL Server端,本地CLR DateTime映射为datedatetimedatetime2类型,TimeSpan映射为time类型。

AM / PM指示符是12-hour clock格式的DateTime文本表示的概念。它不是DateTime值的部分可能属于DateTime值的字符串表示形式。 TimeSpan无法用AM或PM表示,因为它是时间间隔。这就是为什么,你不能这样说; 中午后7小时3分钟和1秒TimeSpanTimeSpan 不能在中午之前或中午之后。txtdate.Text 因为它是时间间隔

让我们看看你的例子;

看起来你从其他地方得到你的头衔,日期,时间和邮件。在这里我的建议;

如果您真的想要在尝试代表它们时显示AM / PM指示符;

  1. 连接您的txttime.TextDateTime字符串以及parse it to DateTime
  2. 使用datedatetimedatetime2(可选)键入的列将此DateTime.ToString()值保存到您的数据库中。
  3. 当您尝试表示此值时,请从数据库中选择它,使用tt方法和custom date and time format说明符(对于AM / PM指示符datetimeValue.ToString("HH:mm tt", CultureInfo.InvariantCulture))具有特定文化。例如; {{1}}
  4. 在创建动态sql命令时,应始终使用parameterized queries。这种字符串连接对SQL Injection攻击开放。

    还建议阅读:Bad habits to kick : choosing the wrong data type

答案 1 :(得分:0)

试试这个

DateTime now = DateTime.Now;
now.ToString("yyyy-MM-dd HH:mm:ss"); //Outputs 2014-04-08 12:50:35
now.ToString("HH:mm:ss"); //Will then output 12:50:35