简体   繁体   中英

Converting year month day to date in sql server

My input to the stored procedure is a string (eg '2 years 3 months 4 days') which is a future date. How to convert this to a date by comparing with current date?

declare @S varchar(50)
set @S = '2 years 3 months 4 days'

select dateadd(day, D.D, dateadd(month, D.M, dateadd(year, D.Y, getdate()))) as TheDate
from (select replace(replace(replace(@S, ' years ', '.'), ' months ', '.'), ' days', '')) as T(S)
  cross apply (
              select cast(parsename(T.S, 1) as int),
                     cast(parsename(T.S, 2) as int),
                     cast(parsename(T.S, 3) as int)Y
              ) as D(D, M, Y)

SQL Fiddle

You can use below Query in SP

select dateadd(yy,2,dateadd(m,3,dateadd(d,4,GETDATE())))
                  ^Year       ^Month      ^Days

Here is the SP

create procedure test1
(
@year INT,
@month INT,
@day INT
)
AS
BEGIN
    select dateadd(yy,@year,dateadd(m,@month,dateadd(d,@day,GETDATE())))
END

Use DATEADD , for example (add one year, to the current data):

DECLARE @datetime2 datetime2 = getdate();
SELECT 'year', DATEADD(year,1,@datetime2)
...

So, you should add 2 years, 3 months and 4 days to the current date and then return it as normal date (here I returned future year). Read here for details.

Before of the stored procedure invocation you should split the string in a server side language like PHP:

$str = '2 years 3 months 4 days';
preg_match_all('!\d+!', $str, $data);

So $data[0]=2, $data[1]=3 and $data[2] = 4 , and so you can invoke @Luv procedure:

create procedure test1 -- thanks to Luv
(
@year INT,
@month INT,
@day INT
)
AS
BEGIN
    select dateadd(yy,@year,dateadd(m,@month,dateadd(d,@day,GETDATE())))
END

https://dev.mysql.com/doc/refman/5.5/en/date-and-time-functions.html Convert seconds to human readable time duration

you may be able to split & convert this formatting into something which is useable via builtin SQL-functions - but i'd recommend using at least a pre-processing scriptlanguage like PHP in order to format the time correctly, PHP "relative" formats may just be the thing, i recall the datetime-class being quite powerful ...

http://www.php.net/manual/en/datetime.construct.php
http://www.php.net/manual/en/datetime.formats.relative.php
http://www.php.net/manual/en/datetime.formats.compound.php

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM