-- 常用时间函数GETDATE():
SELECT GETDATE(); -- 获取当前日期,如2024-06-17 16:23:07.253
SELECT YEAR(GetDate()) as '年';
SELECT MONTH(GetDate()) as '月';
SELECT DAY(GetDate()) as '日';
-- GETDATE+DATEPART() 函数用于返回日期/时间的单独部分,返回整数。获取年、月、日、小时、分钟等。
SELECT DatePart(YY,GETDATE())as '年';
SELECT DatePart(mm,GETDATE())as '月';
SELECT DatePart(dd,GETDATE())as '日';
SELECT DatePart(hh,GETDATE())as '时';
-- GETDATE+DATENAME函数返回指定日期的指定部分,返回字符串。获取年、月、日、星期、周数、时、分、秒;
SELECT DateName(YEAR,GetDate()) as '年';
SELECT DateName(MONTH,GetDate()) as '月';
SELECT DateName(DAY,GetDate()) as '日';
SELECT DateName(hour,GetDate()) as '时';
SELECT DateName(minute,GetDate()) as '分';
SELECT DateName(second,GetDate()) as '秒';
SELECT DateName(weekday,GetDate()) as '星期';
SELECT DateName(quarter,GetDate()) as '第几季度';
SELECT DateName(week,GetDate()) as '一年中的第几周';
SELECT DateName(DAYOFYEAR,GetDate()) as '一年中的第几天';
-- GETDATE+DATEADD()函数,在日期中添加或减去指定的时间间隔。年、月、日+1
SELECT DATEADD(year,1,GETDATE()) as 明年今日;
SELECT DATEADD(year,-1,GETDATE()) as 去年今日;
SELECT DATEADD(month,+1,GETDATE()) as 下月今日;
SELECT DATEADD(day,30,GETDATE()) as XX天后;
-- GETDATE+DATEDIFF()函数返回两个指定日期之间间隔的时间
SELECT DATEDIFF(year,'2023-01-01' ,GETDATE()) as "间隔时间/年";
SELECT DATEDIFF(month,'2023-01-01' ,GETDATE()) as "间隔时间/月";
SELECT DATEDIFF(day,'2023-01-01',GETDATE()) as "间隔时间/天";
SELECT DATEDIFF(day,'2023-01-01','2023-01-02') as "间隔时间/天";
SELECT DATEDIFF(hh,'2024-07-23 14:55:24.130',GETDATE());-- 间隔时间/小时
-- PS:where DateDiff(hh,CreateDate,getDate())<=24
-- GETDATE+CONVERT()函数可以用不同的格式去显示日期/时间数据, 把日期转换为新数据类型的通用函数。
SELECT CONVERT(VARCHAR(12),GETDATE(),102); -- 2024.06.17
SELECT CONVERT(VARCHAR(10),GETDATE(),121); -- 2024-06-17
SELECT CONVERT(VARCHAR(23),GETDATE(),120) as 输出时间格式; -- 2024-06-17 16:24:05
-- GETDATE+EOMONTH函数返回包含指定日期所在月份的最后一天。
SELECT EOMONTH( '2023-12-01' );
SELECT EOMONTH( GETDATE() ) as 当月月末日期;
-- CAST函数用于转换数据类型
-- select cast(字段 as varchar) from 表名;
-- select convert(varchar(50),字段) from 表名;
SELECT CAST(10.2748 as int) as 取整;
SELECT CAST(12345.22 as float);
SELECT CAST(12345.12345 as char);
SELECT CAST('2023-12-18 15:41:25' as char(16)); -- 2023-12-18 15:41 ,刚好16字符
SELECT CAST(GetDate() as datetime2); -- 2024-06-17 16:26:08.6766667
SELECT CAST(NEWID() AS varchar(36)) as 随机字符串; -- 15E01CED-3C02-436F-A5C0-B7B89F746A8E
-- REPLACE函数使用新字符串替换字符串所有出现的子字符串,时间格式替换。
SELECT REPLACE(CONVERT(varchar, GETDATE(), 120 ),'-','/') -- 2024/06/17 16:28:02
--PS:时间转化为字符串
SELECT CAST(DateName(MONTH,GetDate()) AS NVARCHAR(2))+CAST(DateName(DAY,GetDate()) AS NVARCHAR(2))+REPLACE(CONVERT(varchar, GETDATE(), 108 ),':','') -- 072114941
SELECT REPLACE(REPLACE(REPLACE(CONVERT(varchar, GETDATE(), 120 ),'-',''),':',''),' ','') -- 20240702114932
SELECT CAST(DateName(MONTH,GetDate()) AS NVARCHAR(2))+RIGHT('00'+CAST(DateName(Day,GetDate()) AS NVARCHAR(2)),2)+CAST(DateName(hour,GetDate()) AS NVARCHAR(2))+CAST(DateName(minute,GetDate()) AS NVARCHAR(2)) -- 07021345