生产系统分早晚班问题,经约定,每天七点之前,所有生产记录,算前一天处理。因为系统记录产生的日期,是获取当前日期,需要改写一下,七点之前的取到的当天日期需要减去1天。解决方法可以多种,前台程序处理,或是可以数据库中处理。
程序处理:
GetGenerateDate
string GetGenerateDate()
{
DateTime dateTime1 = DateTime.Now;
DateTime dateTime2 = Convert.ToDateTime(dateTime1.ToString("yyyy-MM-dd") + " " + "07:00:00");
if (DateTime.Compare(dateTime1, dateTime2) < 0)
{
dateTime1 = dateTime1.AddDays(-1);
}
return dateTime1.ToString("yyyy-MM-dd");
}
{
DateTime dateTime1 = DateTime.Now;
DateTime dateTime2 = Convert.ToDateTime(dateTime1.ToString("yyyy-MM-dd") + " " + "07:00:00");
if (DateTime.Compare(dateTime1, dateTime2) < 0)
{
dateTime1 = dateTime1.AddDays(-1);
}
return dateTime1.ToString("yyyy-MM-dd");
}
数据库端处理,和前台程序的函数基本上一样:
udf_GetGenerateDate
CREATE FUNCTION [dbo].[udf_GetGenerateDate]()
RETURNS DATE
AS
BEGIN
DECLARE @d DATETIME = CURRENT_TIMESTAMP
DECLARE @d2 DATETIME = CONVERT(DATETIME,CONVERT(NVARCHAR(20),CAST(@d AS DATE)) + ' ' + '07:00:00')
--下面这个函数,可以参考链接:
--http://www.cnblogs.com/insus/archive/2011/06/24/2089005.html
IF ([dbo].[DateTimeCompare](@d,@d2) < 0)
SET @d = DATEADD(day,-1,@d)
RETURN CAST(@d AS TIME)
END
RETURNS DATE
AS
BEGIN
DECLARE @d DATETIME = CURRENT_TIMESTAMP
DECLARE @d2 DATETIME = CONVERT(DATETIME,CONVERT(NVARCHAR(20),CAST(@d AS DATE)) + ' ' + '07:00:00')
--下面这个函数,可以参考链接:
--http://www.cnblogs.com/insus/archive/2011/06/24/2089005.html
IF ([dbo].[DateTimeCompare](@d,@d2) < 0)
SET @d = DATEADD(day,-1,@d)
RETURN CAST(@d AS TIME)
END
另外一种方法,也是在数据库中处理,也许要比上一个函数,简单得多,只是判断当前的时间是否是在0点到7点之间,如果是,日期减1天:
udf_GetGenerateDate
CREATE FUNCTION [dbo].[udf_GetGenerateDate]()
RETURNS DATE
AS
BEGIN
DECLARE @TimeStamp TIME = '07:00:00'
DECLARE @cDate DATETIME = CURRENT_TIMESTAMP
IF (CAST(@cDate AS TIME) BETWEEN '00:00:00' AND @TimeStamp)
SET @cDate = DATEADD(day,-1,@cDate)
RETURN CAST(@cDate AS DATE)
END
RETURNS DATE
AS
BEGIN
DECLARE @TimeStamp TIME = '07:00:00'
DECLARE @cDate DATETIME = CURRENT_TIMESTAMP
IF (CAST(@cDate AS TIME) BETWEEN '00:00:00' AND @TimeStamp)
SET @cDate = DATEADD(day,-1,@cDate)
RETURN CAST(@cDate AS DATE)
END