Mytutorialrack

Apex Date Class

In Apex programming, the Date class is a built-in class that represents a date without a time component. The Apex Date class provides powerful functionalities for handling and manipulating dates in Salesforce development.

Here are some key features and uses of the Date class in Apex:

  1. Date Creation: You can create a Date object using the Date.newInstance(year, month, day) method, where you specify the year, month, and day as integers.
  2. Date Manipulation: The Date class provides methods to manipulate dates, such as addDays(), addMonths(), and addYears(), which allow you to add a specified number of days, months, or years to a given date.
  3. Date Comparison: You can compare dates using operators like ==, <, >, etc., to determine if one date is equal, earlier, or later than another date.
  4. Date Formatting: The format() method allows you to format a Date object as a string according to the locale of the context user.
  5. Retrieving Date Components: The Date class offers methods like day(), month(), and year() to extract specific components of a date, such as the day of the month, month, and year.
  6. Date Calculations: The Date class provides methods like daysBetween(), monthsBetween(), and dayOfYear() to calculate the number of days between two dates, the number of months between two dates, or the day of the year for a given date.
  7. Date Validation: The isLeapYear(year) method can be used to determine whether a specified year is a leap year or not.

By using the Date class and its methods, you can perform various date-related operations, calculations, and validations in your Apex code.

Apex Date Class Methods

Here are the methods available for the Date class:

  • addDays(additionalDays): Adds the specified number of additional days to a Date.
  • addMonths(additionalMonths): Adds the specified number of additional months to a Date.
  • addYears(additionalYears): Adds the specified number of additional years to a Date.
  • day(): Returns the day-of-month component of a Date.
  • dayOfYear(): Returns the day-of-year component of a Date.
  • daysBetween(secondDate): Returns the number of days between the Date that called the method and the specified date.
  • daysInMonth(year, month): Returns the number of days in the month for the specified year and month (1=Jan).
  • format(): Returns the Date as a string using the locale of the context user.
  • isLeapYear(year): Returns true if the specified year is a leap year.
  • isSameDay(dateToCompare): Returns true if the Date that called the method is the same as the specified date.
  • month(): Returns the month component of a Date (1=Jan).
  • monthsBetween(secondDate): Returns the number of months between the Date that called the method and the specified date, ignoring the difference in days.
  • newInstance(year, month, day): Constructs a Date from Integer representations of the year, month (1=Jan), and day.
  • parse(stringDate): Constructs a Date from a String. The format of the String depends on the local date format.
  • today(): Returns the current date in the current user’s time zone.
  • toStartOfMonth(): Returns the first of the month for the Date that called the method.
  • toStartOfWeek(): Returns the start of the week for the Date that called the method, depending on the context user’s locale.
  • valueOf(stringDate): Returns a Date that contains the value of the specified String.
  • valueOf(fieldValue): Converts the specified object to a Date. Use this method to convert a history tracking field value or an object that represents a Date value.
  • year(): Returns the year component of a Date.

Date Class in Apex with Example

// Create a new Date object
Date myDate = Date.newInstance(2023, 6, 7);
System.debug('My Date: ' + myDate);

// Add 10 days to the date
Date futureDate = myDate.addDays(10);
System.debug('Future Date: ' + futureDate);

// Get the month of the date
Integer month = myDate.month();
System.debug('Month: ' + month);

// Get the day of the year
Integer dayOfYear = myDate.dayOfYear();
System.debug('Day of Year: ' + dayOfYear);

// Check if it's a leap year
Boolean isLeapYear = Date.isLeapYear(myDate.year());
System.debug('Is Leap Year? ' + isLeapYear);

// Calculate the number of days between two dates
Date secondDate = Date.newInstance(2023, 6, 15);
Integer daysBetween = myDate.daysBetween(secondDate);
System.debug('Days Between: ' + daysBetween);

// Format the date as a string
String formattedDate = myDate.format();
System.debug('Formatted Date: ' + formattedDate);

// Get the current date
Date currentDate = Date.today();
System.debug('Current Date: ' + currentDate);

// Get the start of the month for the date
Date startOfMonth = myDate.toStartOfMonth();
System.debug('Start of Month: ' + startOfMonth);

// Get the start of the week for the date
Date startOfWeek = myDate.toStartOfWeek();
System.debug('Start of Week: ' + startOfWeek);

How to convert String into Date format in Apex Class ?

String dateString = '2023-06-07';
Date convertedDate = Date.valueOf(dateString);
System.debug('Converted Date: ' + convertedDate);

How to pass date as a parameters in Apex class ?

public class DateExample {
public static Date processDate(Date inputDate) {
        // Perform operations with the inputDate parameter
       Date newDate=inputDate.addDays(10);
      return newDate;
    }
}

Run below code in Anonymous Apex:

Date myDate = Date.newInstance(2023, 6, 7);
Date processedDate=DateExample.processDate(myDate);
System.debug('proceesedDate '+processedDate);

How to pass date in Apex Test class ?

@IsTest

public class DateExampleTest {
   @IsTest
    public static void testProcessDate() {
        Date myDate = Date.newInstance(2023, 6, 7);
        Date add10Days=myDate.addDays(10);
        Date processedDate=DateExample.processDate(myDate);
        
        // Add assertions to validate the expected results
        System.assertEquals(add10Days, processedDate, 'Incorrect processed date');
    }
}
Enroll in our Salesforce Development Training Course

Share:

Recent Posts