我想将我的 Hijri Shamsi 日期“92/2/3”转换为这种格式:“92/02/03”
使用此代码,我收到此错误:将 varchar 数据类型转换为 datetime 数据类型导致值超出范围。
Declare @Str Varchar(10) = '92/2/3'
Select Convert(Varchar(10), Convert(DateTime, @Str), 111)
如何更改日期格式?
11
,而不是111
你的转换代码您需要在内部转换中使用 11 来告诉它它转换的格式是什么
Declare @Str Varchar(10) = '92/2/3'
Select Convert(Varchar(10), Convert(DateTime, @Str,11), 11)
使用此函数以您请求的格式将公历日期转换为回历(Shamsi)日期:
CREATE FUNCTION [dbo].[ShamsiDate]
(
@ChirsDate SMALLDATETIME
)
RETURNS CHAR(10)
AS
BEGIN
DECLARE @SolarDate CHAR(10)
DECLARE @Day CHAR(2)
DECLARE @Mon CHAR(2)
DECLARE @SDay INT
DECLARE @SMon INT
DECLARE @SYear INT
SET @SYear = dbo.ShamsiDatePart(@ChirsDate, 'Y')
SET @SMon = dbo.ShamsiDatePart(@ChirsDate, 'M')
SET @SDay = dbo.ShamsiDatePart(@ChirsDate, 'D')
IF @SMon <= 9
SELECT @Mon = '0' + CONVERT(CHAR(1), @SMon)
ELSE
SELECT @Mon = CONVERT(CHAR(2), @SMon)
IF @SDay <= 9
SELECT @Day = '0' + CONVERT(CHAR(1), @SDay)
ELSE
SELECT @Day = CONVERT(CHAR(2), @SDay)
SELECT @SolarDate = CONVERT(CHAR(4), @SYear) + '/' + @Mon + '/'
+ @Day
RETURN @SolarDate
END
CREATE FUNCTION [dbo].[ShamsiDatePart]
(
@MiDate DATETIME ,
@ADatePart CHAR
)
RETURNS INT
AS
BEGIN
DECLARE @TmpY INT ,
@Leap INT
DECLARE @Sh_Y INT ,
@Sh_M INT ,
@Sh_D INT ,
@Result INT
IF @MiDate IS NULL
RETURN 0
DECLARE @Result INT
SET @Result = CONVERT(INT, CONVERT(FLOAT, @MiDate))
IF @Result <= 78
BEGIN
SET @Sh_Y = 1278
SET @Sh_M = ( @Result + 10 ) / 30 + 10
SET @Sh_D = ( @Result + 10 ) % 30 + 1
END
ELSE
BEGIN
SET @Result = @Result - 78
SET @Sh_Y = 1279
WHILE 1 = 1
BEGIN
SET @TmpY = @Sh_Y + 11
SET @TmpY = @TmpY - ( @TmpY / 33 ) * 33
IF ( @TmpY <> 32 )
AND ( ( @TmpY / 4 ) * 4 = @TmpY )
SET @Leap = 1
ELSE
SET @Leap = 0
IF @Result <= ( 365 + @Leap )
BREAK
SET @Result = @Result - ( 365 + @Leap )
SET @Sh_Y = @Sh_Y + 1
END
IF @Result <= 31 * 6
BEGIN
SET @Sh_M = ( @Result - 1 ) / 31 + 1
SET @Sh_D = ( @Result - 1 ) % 31 + 1
END
ELSE
BEGIN
SET @Sh_M = ( ( @Result - 1 ) - 31 * 6 ) / 30 + 7
SET @Sh_D = ( ( @Result - 1 ) - 31 * 6 ) % 30 + 1
END
END
RETURN CASE @ADatePart WHEN 'Y' THEN @Sh_Y WHEN 'M' THEN @Sh_M WHEN 'D' THEN @Sh_D ELSE 0 END
END
如果您使用的是 SQL Server 2012,则可以使用以下解决方案。
Declare @Str varchar(10) = '92/2/3'
Select Format(Convert(Date, @Str,11),'yy/MM/dd')
伊姆兰