Receive date as "19-May" and need to convert it as '05/01/2019', "19-June" to '06/01/2019'.
I have tried various date conversion but it didn't work.
You can try this. Storing date in this format is not a good/suggestion you should use the proper data type which are meant and available for.
You should update the values with proper date time value and then change the data type also. It will save your time & you do not need these conversions every time.
Select Try_Cast('19-May 2019' as Datetime)
OR
Select Try_Cast('19-May' + '2019' as Datetime)
To get the first date of month you can try the below query.
SELECT DATEADD(month, DATEDIFF(month, 0, Try_Cast('19-May 2019' as Datetime)), 0) AS StartOfMonth
Edit
To get the first date of month as per the given data in string, you can use the below query.
declare #dateinStr varchar(20) = '19-May'
Select try_cast('01-' + Replace(#dateinStr, LEFT(#dateinStr, 3), '') + LEFT(#dateinStr, 2) as Datetime) as Date
Here is the demo.
I suppose the months will be 3 chars only, if so then
Select s,
try_Cast(concat(right(s, 3), ' 2019') as Datetime)
from
(
values
('19-May'),
('19-Jun')
) t(s);
If the months is really comes like "June" & "August" then
select s,
try_cast(concat(substring(s, charindex('-',s)+1, 3), ' 2019') as date)
from
(
values
('19-May'),
('19-June'),
('15-August')
) t(s);
If you need to format it as mm/dd/yyyy then use 101 style.
You can do :
SELECT DATEADD(DAY, 1, EOMONTH(CONVERT(DATE, Dates + '-2019'), -1))
FROM ( VALUES ('19-May'), ('19-June')
) t(Dates);
Related
I have a column ENTRY_MONTH with dates in it as a string like 11/2017.
I'm trying to convert the column to datetime, preferably the last day of each month, so in the example above would be 11-30-2017.
I've tried
CONVERT(datetime, ENTRY_MONTH, 110)
to no avail. Any advice?
select convert(datetime,right(entrymonth,4) + left(entrymonth,2) + '01')
There are so many ways to do this.
Declare #strDate varchar(10) = '11/2017'
-- concatenate '01/' to get the first date of the month.
-- (it is needed to make a proper date,
-- and not necessary to make it the first date, it can be '17/' as well
Select '01/' + #strDate
Select Convert(DateTime,'01/' + #strDate, 103)
-- the EOMONTH can be used here
Select EOMONTH(Convert(DateTime,'01/' + #strDate, 103))
in your case:
EOMONTH(Convert(DateTime,'01/' + ENTRY_MONTH, 103)
You can try something like:
DECLARE #MyDate varchar(16) = '11/2017'
SELECT DATEADD(d,-1,DATEADD(m,1,CONVERT(datetime, '1/' + #MyDate, 103)))
This uses a European format where the day comes first. Add a month on then take a day off takes you to the end of the month.
If you go step by step converting and formatting, you can do it like this (intermediate results shown in the result, too):
DECLARE #entryMonth VARCHAR(7) = '11/2017';
SELECT
#entryMonth AS "entry month",
FORMAT( -- create a date from the parts you have in the varchar and a 1 for the day
DATEFROMPARTS(RIGHT(#entryMonth, 4), LEFT(#entryMonth, 2), 1),
'MM-dd-yyyy' -- and format it the way you want
) AS "First of month",
FORMAT(
DATEADD(MONTH,
1, -- add a month in order to get the first of next month
FORMAT(
DATEFROMPARTS(RIGHT(#entryMonth, 4), LEFT(#entryMonth, 2), 1),
'MM-dd-yyyy')
),
'MM-dd-yyyy'
) AS "First day next month",
FORMAT(
DATEADD(DAY,
-1, -- subtract a day from the first of next month
DATEADD(MONTH, 1, FORMAT(
DATEFROMPARTS(RIGHT(#entryMonth, 4), LEFT(#entryMonth, 2), 1),
'MM-dd-yyyy'))
),
'MM-dd-yyyy'
) AS "Last day entry month"
entry month First of month First day next month Last day entry month
11/2017 11-01-2017 12-01-2017 11-30-2017
IF I Select #rpmMonth = SEP 2019 it should pull the data from JAN 2019 to SEP 2019
**I Have only One Parameter Value i.e #rpmMonth of VARCHAR Type.
Declare #firstDay Date=(
select convert(varchar(10),DATEADD(Year,-1*DateDiff(Year,getdate(),0),0),120))
Declare #CurDate Date=(
SELECT convert(varchar(10),DATEADD(s,-1,DATEADD(mm, DATEDIFF(m,0,GETDATE())+1,0)),120))
select * from YOURTABLE
where colname between #firstDay and #CurDate
Ideally, you should be using a date datatype, not a varchar. If we do, however, have to use a varchar then you could do something like this:
SELECT {Columns}
FROM {Your Schema And Table}
WHERE {DateColumn} >= CONVERT(date,CONCAT(RIGHT(#rpmMonth),'0101'))
AND {DateColumn} < DATEADD(MONTH, 1, CONVERT(date, '01 ' + #rpmMonth));
(Obviously replace the parts in braces ({}) and assumes the language of the LOGIN is an English based language.)
This would give you all rows on or after Jan 01 of the year for #rpmMonth and before the month after #rpmMonth.
If you use a proper date, and pass the first date of the month i.e. (2019-09-01 for the sample you gave), then you could do the below:
SELECT {Columns}
FROM {Your Schema And Table}
WHERE {DateColumn} >= DATEADD(YEAR, DATEDIFF(YEAR, 0, #rpmMonth),0)
AND {DateColumn} < DATEADD(MONTH, 1, #rpmMonth);
SQL Server is pretty good about converting date values. You should be able to do:
select . . .
from t cross join
(values (convert(date, #rpmMonth)) as v(dte)
where datecol >= datefromparts(year(v.dte), 1, 1) and
datecol < datefromparts(year(dateadd(month, 1, v.dte)), month(dateadd(month, 1, v.dte)), 1)
How can I subtract one month from mm/yy in SQL?
For an example from 02/23 to 01/23.
Since your date format is not the recommended one. But for your scenario, you can use the following query to get your expected result.
Using DATEFROMPARTS() and string functions you can construct as a date and the DATEADD(MONTH, -1, date) will help to subtract one month.
DECLARE #TestTable TABLE (DateVal VARCHAR(5));
INSERT INTO #TestTable (DateVal) VALUES ('02/23'), ('01/23'), ('03/30');
SELECT DateVal,
RIGHT(CONVERT(VARCHAR(8), DATEADD(MONTH, -1, DATEFROMPARTS(RIGHT(DateVal, 2), LEFT(DateVal, 2), '01')), 3), 5) AS Result
FROM #TestTable
Result:
DateVal Result
----------------------
02/23 01/23
01/23 12/22
03/30 02/30
Demo on db<>fiddle
I think you need to use convert() to get a valid date, then dateadd() to subtract 1 month and finally format() to get the date in the string format:
select
format(dateadd(month, -1, convert(date, concat('01/', datecolumnname), 3)), 'MM/yy')
from tablename
See the demo.
This comes with a warning is super ugly but if you want string previous month then string again, maybe convert to date do the dateadd then back to string, horrid!
with cte_d
as
(select '01/23' as stringdate
union
select '12/17' as stringdate
)
select stringdate
,cast(Month(dateadd(month,-1,cast(right(stringdate,2)
+ left(stringdate,2) + '01' as date))) as nvarchar(2))
+'/'+
right(cast(Year(dateadd(month,-1,cast(right(stringdate,2)
+ left(stringdate,2) + '01' as date))) as nvarchar(4)),2) as [NewDate]
from cte_d
I have 2 columns in a table of varchar datatype.
date and type are the column names in table.
the data present in the table looks like this
date time
20090610 132713
20090610 132734
i need ms sql server query to concatenate these 2 columns data and display as datetime format.
Note :
1. the datatype of those 2 columns cannot be changed now.
2. i tried
select convert(datetime,date + time)
it says "Conversion failed when converting date and/or time from character string."
Suggest the possible solution.
This will return a datetime. The bottom line is to be replaced by your table
select convert(datetime,date,112)+
coalesce(stuff(stuff(rtrim(time), 5,0,':'), 3,0,':'), '') newdate
from
(VALUES ('20090610','132713'),('20090610', '132734'),('20090610', ' ')) yourtable(date,time)
Result:
newdate
2009-06-10 13:27:13.000
2009-06-10 13:27:34.000
2009-06-10 00:00:00.000
You can get it using
SELECT
convert(varchar, convert(datetime, date), 111)
+ ' ' + substring(time, 1, 2)
+ ':' + substring(time, 3, 2)
+ ':' + substring(time, 5, 2)
CREATE TABLE #Table
(
[date] VARCHAR(100),
[time] VARCHAR(100)
)
INSERT INTO #Table VALUES
('20090610','132713'),
('20090610','132734')
;WITH Bits_CTE
AS
(
SELECT
[Date],
[Time],
[hrs] = CONVERT(INT,SUBSTRING([Time], 1, 2)),
[mns] = CONVERT(INT,SUBSTRING([Time], 3, 2)),
[secs] = CONVERT(INT,SUBSTRING([Time], 5, 2))
FROM #Table
)
SELECT
[Date],
[Time],
DATEADD(HOUR,[hrs],
DATEADD(MINUTE,[mns],
DATEADD(SECOND,[secs],[Date])))
FROM Bits_CTE
CREATE FUNCTION [dbo].[DateTimeAdd]
(
#datepart date,
#timepart time
)
RETURNS datetime2
AS
BEGIN
RETURN DATEADD(dd, DATEDIFF(dd, 0, #datepart), CAST(#timepart AS datetime2));
END
Sorry - Missed the bit in your question about storing the date and time as varchars. You would therefore still need to convert these data itemsbefore using this function.
I have this query
select CONVERT(varchar(5), tdate ,108) AS [Time] from table
which gives me the time in 24 hour format( military)
I wanted to convert it into a 12 hour format so i tried the query below
select SUBSTRING(CONVERT(VARCHAR, tdate, 100),13,2) + ':'
+ SUBSTRING(CONVERT(VARCHAR, tdate, 100),16,2) + ''
+ SUBSTRING(CONVERT(VARCHAR, tdate, 100),18,2) AS T
from table
and i get the 12 hour format but I am just curious if there is a shorter or better way of doing it. any help?
If you want to convert the current datetime for example:
SELECT CONVERT(VARCHAR, getdate(), 100) AS DateTime_In_12h_Format
Instead of getdate() you can put your desired column in a query (such as tdate in your example). If you want JUST the time in 12h and not the date and time use substring/right to separate them. It seems that you already know how to =).
This page lists every datetime conversion. It's really handy if you need other types of conversions.
This will return just the time, not the date.
SELECT RIGHT(CONVERT(VARCHAR, getdate(), 100), 7) AS time
For your table data:
select RIGHT(CONVERT(varchar, tdate ,100), 7) AS [Time] from table
Below code will return only time like 10:30 PM
SELECT FORMAT(CAST(getdate() AS DATETIME),'hh:mm tt') AS [Time]
Get date of server
SELECT LTRIM(RIGHT(CONVERT(VARCHAR(20), GETDATE(), 100), 7))
or
If it is stored in the table
SELECT LTRIM(RIGHT(CONVERT(VARCHAR(20), datename, 100), 7))
Result:
11:41AM
ifnull(date_format(at.date_time,'%d/%m/%Y'),"") AS date_time,
ifnull(time_format(at.date_time ,'%h:%i:%s'),"") AS date_time
This is how a SQL procedure looks...(for separating date and time)..there is no need of a special column for time/date....
Note:if H instead of h it will show the "hour in 24 hour" format