在sql中比较时间(或日期)的最佳方法是什么?

时间:2022-11-08 16:57:46

I need two comparisons in my Sql server, One between Dates and One between Times. I'm using C# and Sql Server and Linq-to-sql. I want to store two time fields (Enter-Time, Exit-Time). Now I want to get the difference (e.g. 12:30 , 18:15 the difference is 5:45). What Data Type should I use? I have the same issue with Dates, I want to get the difference of two Dates but "DateTime" Data Type stores redundant data about time, I just need date. I want the easiest way with the least code possible. I'm currently saving like this "1045" when I fetch it I add a ":" to the middle and it becomes "10:45" and there are lot's of problems this way.

我需要在Sql服务器中进行两次比较,一次是日期之间的比较,另一次是时间之间的比较。我正在使用c#和Sql Server以及linqto - Sql。我想存储两个时间字段(entertime, exittime)。现在我想知道区别(例如12:30,18:15,差是5:45)。我应该使用什么数据类型?我对日期也有同样的问题,我想要得到两个日期的差值,但是“DateTime”数据类型存储时间上的冗余数据,我只需要日期。我想要最简单的方法,用最少的代码。我现在像这样保存“1045”当我取回它时,我在中间添加了一个“:”,它变成了“10:45”,这样就有很多问题。

2 个解决方案

#1


3  

If you need to store dates, you can use the date datatype. Similarly for times, you can use the time datatype.

如果需要存储日期,可以使用日期数据类型。类似地,对于times,您可以使用time datatype。

To compute the difference, you can use the DATEDIFF() sql function that returns the difference between two dates: http://msdn.microsoft.com/en-us/library/ms189794.aspx

要计算差异,可以使用DATEDIFF() sql函数,它返回两个日期之间的差异:http://msdn.microsoft.com/en-us/library/ms189794.aspx

I would advise against storing your data as a string, int etc. Use the datatypes as they are intended.

我建议不要将数据存储为字符串、int等格式。按照需要使用数据类型。

#2


1  

For storing the data, you can use a Date type, or Time type. Once you do this the TimeSpan structure can be used (in your application) to measure differences in time/dates. If you subtract one date from another then you will receive a TimeSpan object back.

为了存储数据,可以使用日期类型或时间类型。这样做之后,可以使用TimeSpan结构(在应用程序中)来度量时间/日期的差异。如果你从另一个日期减去一个日期,你就会得到一个TimeSpan对象。

var difference = Date1.Subtract(Date2);

#1


3  

If you need to store dates, you can use the date datatype. Similarly for times, you can use the time datatype.

如果需要存储日期,可以使用日期数据类型。类似地,对于times,您可以使用time datatype。

To compute the difference, you can use the DATEDIFF() sql function that returns the difference between two dates: http://msdn.microsoft.com/en-us/library/ms189794.aspx

要计算差异,可以使用DATEDIFF() sql函数,它返回两个日期之间的差异:http://msdn.microsoft.com/en-us/library/ms189794.aspx

I would advise against storing your data as a string, int etc. Use the datatypes as they are intended.

我建议不要将数据存储为字符串、int等格式。按照需要使用数据类型。

#2


1  

For storing the data, you can use a Date type, or Time type. Once you do this the TimeSpan structure can be used (in your application) to measure differences in time/dates. If you subtract one date from another then you will receive a TimeSpan object back.

为了存储数据,可以使用日期类型或时间类型。这样做之后,可以使用TimeSpan结构(在应用程序中)来度量时间/日期的差异。如果你从另一个日期减去一个日期,你就会得到一个TimeSpan对象。

var difference = Date1.Subtract(Date2);