6

I have the following piece of SQL:

select DATEADD(s,-1,DATEADD(mm, DATEDIFF(m,0,GETDATE()),0))

which comes through as this format:

2012-02-29 23:59:59.000

I need the exact piece of code with the date the same, however the time part must read 00:00:00.000

Modify* I should have been clear here: I need to have the last day of previous month at any given time (with the time in 00:00:00.000 format of course)

Darren
  • 68,902
  • 24
  • 138
  • 144
JsonStatham
  • 9,770
  • 27
  • 100
  • 181
  • possible duplicate of [Floor a date in SQL server](http://stackoverflow.com/questions/85373/floor-a-date-in-sql-server) – Hogan Mar 29 '12 at 11:01
  • `SELECT CAST(s AS DATE)` or `SELECT CAST(CAST(s As Date) As DateTime)`? – Seph Mar 29 '12 at 11:35

6 Answers6

5
select dateadd(d,datediff(d,0,dateadd(s,-1,dateadd(m,datediff(m,0,getdate()),0))),0)
general exception
  • 4,202
  • 9
  • 54
  • 82
3
SELECT DATEADD(MONTH, -1, DATEADD(DAY, 0, DATEDIFF(DAY, 0, GETDATE())))
Darren
  • 68,902
  • 24
  • 138
  • 144
3

This will give you the last second of the prior month

select dateadd(s,-1,dateadd(month,datediff(month,0,GETDATE()),0));

and this will give you the last day of the prior month

select dateadd(day,-1,dateadd(month,datediff(month,0,GETDATE()),0));

More details of how to do this:

select dateadd(day,datediff(day,0,@datetime),0);

or

select dateadd(day,datediff(day,0,GETDATE()),0);

In English: Take the number of days between this date and 0 and add those days to 0.

This works with any parameter for datediff. So

select dateadd(month,datediff(month,0,GETDATE()),0);

Will "remove" all day information in addition to time information.

Hogan
  • 69,564
  • 10
  • 76
  • 117
2

An alternative method to strip out the time portion is to cast it to a float, apply the Floor function and cast back to a datetime.

select Cast(Floor(Cast(DATEADD(s,-1,DATEADD(mm, DATEDIFF(m,0,GETDATE()),0)) as float)) as datetime)
codingbadger
  • 42,678
  • 13
  • 95
  • 110
0

Saw some similar posts

select  cast(cast(dateadd(dd,-1,getdate()) as date) as datetime)

Cast your dateadd as a date and then enclose it in another cast back to datetime

So it goes from this 2012-02-29 23:59:59.000

To this 2012-02-29

and the finally this 2012-02-29 00:00:00.000

Dharman
  • 30,962
  • 25
  • 85
  • 135
0
SELECT DATEADD(DAY, -1, DATEADD(MONTH, DATEDIFF(MONTH, 0, GETDATE()), 0))

In SQL Server 2012 you could use eomonth.

SELECT EOMONTH(DATEADD(MONTH, -1, GETDATE()))
Mikael Eriksson
  • 136,425
  • 22
  • 210
  • 281
  • I tried your date you suggested in your comment. It gave the correct output? – Darren Mar 29 '12 at 11:47
  • 2
    @DarrenDavies - Check this out and notice the differences of the dates between our answers and the query provided in the question. [End-Of-Month](http://data.stackexchange.com/stackoverflow/query/65491/end-of-month) – Mikael Eriksson Mar 29 '12 at 12:06