While working as a Salesforce developer, I was assigned a task to build a custom logic that breaks down a date field into its individual components—year, month, and day. This was required so that we could generate customized reports and perform date-based filtering for opportunities.
To solve this, I had to extract the year, month, and day from the custom CloseDate__c field on the Opportunity object.
In this Salesforce tutorial, I will explain how to extract Year, Month, and Day from a Date Filed in Salesforce Apex.
Extract Year, Month, and Day from a Date Field in Salesforce Apex
Salesforce Apex has various approaches and methods to extract and get the Year, Month, and Day from a Date field in Salesforce Apex, which we will discuss in the steps below.
Extract Year, Month, and Day from a Date Field using the Date Class
To get Year, Month, and Day from a Date Field using the Date class, open the Salesforce developer, enter the code below in the Apex anonymous window, and execute it.
Date todayDate = Date.today();
Integer year = todayDate.year();
Integer month = todayDate.month();
Integer day = todayDate.day();
System.debug('Year: ' + year);
System.debug('Month: ' + month);
System.debug('Day: ' + day);
In the execution log window, we will use the date(day), month, and year values extracted from today’s date.

Instead of the today() date, we can also use a specific date to extract the day, month, and year values using the Date class method.
Extract Year, Month, and Day from a Datetime field
In Salesforce, we can use the Datetime class to get the Year, Month, and Date from the Datetime fields.
DateTime dateTimeValue = DateTime.now();
Integer year = dateTimeValue.year();
Integer month = dateTimeValue.month();
Integer day = dateTimeValue.day();
System.debug('Date Year: ' + year);
System.debug('Date Month: ' + month);
System.debug('Date Day: ' + day);
In the execution log window, we can see the values of extracted day, month, and year from the datetime field.
