Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Updating year in datetime variable

I'm playing around with manipulating a datetime variable. I can't seem to find a way to update a datetime variable year to the current year.

For example I have

2007-12-01 00:00:00.000

But I would like that to be

2012-12-01 00:00:00.000    (The current year were in)

I've been playing with datediff, but I can't seem to nail it.

Any advice would be appreciated.

Thanks

like image 679
JGreasley Avatar asked May 11 '12 11:05

JGreasley


People also ask

How can I change the year in DateTime?

DateTime is immutable type. You cannot change year or any other part of it. You should create new DateTime instance with new year.

How can update only year in DateTime in SQL Server?

Update only the YEAR part of a SQL Server date using the DATEADD() function. Let's use the DATEADD() function to update the year from the start_date to a different year. Use the below query to see if we are getting the desired results. We are replacing the year portion of the date with "2019".

How do I change the year of a date in SQL?

To change the year in MySQL date, you need to use DATE_FORMAT() function with UPDATE command. The syntax is as follows. Display all records from the table using select statement.


2 Answers

DECLARE @date datetime = '2007-01-09T12:34:56'
SELECT @date = DATEADD(yyyy, DATEDIFF(yyyy, @date, GETDATE()), @date)

SELECT @date
like image 65
AdaTheDev Avatar answered Sep 28 '22 07:09

AdaTheDev


Maybe something like this:

For sql server 2008+

DECLARE @date DATETIME='2007-12-01 00:00:00.000'
SET @date=DATEADD(year,DATEDIFF(year,@date,GETDATE()),@date)

For sql server 2005

DECLARE @date DATETIME
SET @date='2007-12-01 00:00:00.000'
SET @date=DATEADD(year,DATEDIFF(year,@date,GETDATE()),@date)
like image 26
Arion Avatar answered Sep 28 '22 08:09

Arion