The DatePart function returns a specified part of a date value. In other words, this function can part out the year, month, day, hour, or minute of a date value. A good use case is using the DatePart function and the Now function to always show the current year for the copyright year in the footer. Not to be confused with the DateParse function.
Syntax:
DatePart(1,2)
1 = Date value to retrieve a specified part (can be a variable). Valid values include ‘MM/dd/yyyy’ or ‘YYYY-MM-DD’
2 = Unit of time specified. Valid values include ‘Y’ (year), ‘M’ (month), ‘D’ (day), ‘H’ (hour), ‘MI’ (minute)
Example:
%%[
var @date, @year
set @date = Now()
set @year = DatePart(@date,”y”)
]%%
Copyright © %%=v(@year)=%% AMPscript.com
Output:
Copyright © 2021 AMPscript.com
Explanation:
Using the DatePart function in conjunction with the Now function, the current year can be retrieved and returned. The unit time of difference used in this example is “Y” which returns the year so that the copyright year will not need to be updated every year.
This is exactly what I was looking for! After retrieving the year from a date field, is there ampscript to subtract from the current year? For example, copy reads, “Thanks for being a member since [x] years!”.
Glad to hear that it’s working for you. You can use this DatePart along with the Now() function (https://ampscript.com/now-function/) and the Subtract function (https://ampscript.com/subtract-function/)