我只需要在datetime中格式化(HH:MM) [英] I need only to format (HH:MM) in datetime

查看:267
本文介绍了我只需要在datetime中格式化(HH:MM)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



我只需要在c#

中格式化时间(00-23)和(HH:MM)以及如何在字段Sqlserver 2012中插入此时间

然后获取时间并与另一个字段进行比较?

感谢

Hi
I need only to format time (00-23) & (HH: MM) in c#
and how do I insert this time in field Sqlserver 2012
and then fetch time and compare with another field?
thanks

推荐答案

您可以将Time列值插入TimeSpan。

软件代码: [ ^ ]

you can insert Time column value as TimeSpan.
saple code:[^]
using (SqlConnection cn = new SqlConnection(connstring))
using (SqlCommand cmd = new SqlCommand("Insert into Events (EventName, EventStartTime) values (@Name, @Start)", cn))
{
   cmd.Parameters.AddWithValue("@Name", "Thanksgiving Dinner (East Coast USA)");
   cmd.Parameters.AddWithValue("@Start", new DateTimeOffset(2007, 11, 22, 16, 0, 0, new TimeSpan(-5, 0, 0)));
   cn.Open();

   cmd.ExecuteNonQuery();

}


不要改变任何东西。将日期和时间存储为 DateTime 数据类型。没有办法比较字符串: 22:22 20:15 。哪一个比其他更大或更小?字符串是一个字符串,而不是日期/时间。



您将能够以这种方式比较日期时间数据字段:

SQL

Do not change anything. Store date and time as a DateTime data type. There is no way to compare string: "22:22" to "20:15". Which one is bigger or less than other? String is a string, not date/time.

You'll be able to compare datetime data field this way:
SQL
DECLARE @t1 DATETIME = '2015-01-01 00:00:00'
DECLARE @t2 DATETIME = GETDATE()

SELECT DATEDIFF(HH,@t1,@t2) AS DiffInHrs





C#

DateTime.Compare方法 [ ^ ]




所有DateTime对象都必须有日期和时间。

如果您只想要时间,请使用TimeSpan:

Hi,
All DateTime objects must have a date and a time.
If you want just the time, use TimeSpan:
TimeSpan span = TimeSpan.Parse("01:20");



如果您想要DateTime,请将该时间添加到最小值:


If you want a DateTime, add that time to the min value:

TimeSpan span = TimeSpan.Parse("01:20");
DateTime dt = DateTime.MinValue.Add(span);
// will get you 1/1/1900 01:20 PM which can be formatted with .ToString("HH:mm") for 24 hour formatting


这篇关于我只需要在datetime中格式化(HH:MM)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆