【问题标题】:MSSQL Date FormatMSSQL 日期格式
【发布时间】:2020-08-04 05:03:35
【问题描述】:

我想得到如下的sql日期格式

这是我试过的代码

select case when
left(datepart(day,getdate()),1)=4 then concat(datepart(day,getdate()),'th',' of ',DATENAME(month,GETDATE()),' ',datepart(year,getdate()))
end

这是我 2020 年 8 月 4 日查询的输出

【问题讨论】:

  • 尝试在您的报告设计中使用它: = datepart("d",now())&"th of " & MonthName(month(now())) & " " & datepart("YYYY ",现在())
  • 6 月 1 日或 8 月 3 日有效。
  • @Ashan 。 . .上标应该在应用层处理。
  • 理论上可以编写格式化它的函数,但是一天会有 4 个 case 语句(case 1,21,31 - st, case 2,22 - nd, 3,23 - rd, else - th) 和十个连续字符串

标签: sql sql-server reporting-services


【解决方案1】:
DECLARE @day int = datepart(day,getdate())

SELECT CONCAT(@day,
CASE WHEN @day=1 OR @day=21 OR @day=31 THEN 'st' 
 WHEN @day=2 OR @day=22 THEN 'nd' 
 WHEN @day=3 OR @day=23 THEN 'rd' ELSE 'th' END, ' of ',DATENAME(month,GETDATE()),' ',datepart(year,getdate()) )AS 'Date'

会给你类似的东西。

编辑:如果您将其作为函数,并将日期作为参数传递,您几乎可以在任何地方使用它。然后需要将 getdate() 替换为参数名称

CREATE FUNCTION [dbo].[fnc_GetDateString]
(
    @date DATETIME
)
RETURNS nvarchar(100)
AS
BEGIN
 --DECLARE @date DATETIME = '2020-08-31'
  DECLARE @day int = datepart(day,@date)
  DECLARE @DateString nvarchar(100)
SET @DateString = CONCAT(@day,
CASE WHEN @day=1 OR @day=21 OR @day=31 THEN 'st' 
 WHEN @day=2 OR @day=22 THEN 'nd' 
 WHEN @day=3 OR @day=23 THEN 'rd' ELSE 'th' END, ' of ',DATENAME(month,@date),' ',datepart(year,@date) )

RETURN @DateString
END

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-01-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-10-01
    • 2018-01-17
    • 2015-11-23
    相关资源
    最近更新 更多