Beginner 20 min read

Date, Time, and Datetime

By the end of this lesson, you'll be able to:

  • Distinguish Date, Time, and Datetime
  • Create a Date representing today and a specific day
  • Perform basic date arithmetic

Prerequisites: "Boolean"

Three related but different types

Date today = Date.today();
Datetime rightNow = Datetime.now();
Time noonish = Time.newInstance(12, 30, 0, 0);

Use Date when only the calendar day matters (a birthday, a due date). Use Datetime when the exact moment matters (when a record was created). Time alone is rare in business logic but exists for completeness.

A real business example: Education

Date enrollmentDate = Date.newInstance(2026, 2, 1);
Date courseEndDate = enrollmentDate.addMonths(4);
System.debug(courseEndDate); // 2026-06-01

A student enrollment system only cares about the day a course starts and ends — not the exact second — so Date, not Datetime, is the right fit here.

Basic date arithmetic

Dates support intuitive methods for moving forward or backward in time:

Date today = Date.today();
Date nextWeek = today.addDays(7);
Date lastMonth = today.addMonths(-1);

Under the hood this is just methods on the Date object — no manual "days in a month" math required, and it correctly handles month/year rollovers for you.

Common mistakes

  • Using Datetime when Date is what\'s meant. A Datetime carries time-zone-sensitive time information that can cause a date to appear to shift by a day depending on the viewer's time zone — a classic, hard-to-spot bug for anything that's genuinely just "a day," like a birthday.

Exercise

Declare a Date called projectStart set to today. Calculate and debug a Date 90 days later.

Show hint

Date.today() gives you today; .addDays(90) moves forward.

APEX

Date, Time, and Datetime Quiz

1. Which type would you use for "a patient's date of birth"?

2. Datetime.now() returns only the current calendar day, with no time information.

Log in to submit the quiz and save your score.

My Notes

Log in to keep private notes on this lesson.

Questions about this lesson

No questions yet — be the first to ask.

Log in to ask a question about this lesson.

Summary

Apex splits time-related data into three types: Date (a calendar day, no time), Time (a time of day, no date), and Datetime (both together) — picking the right one avoids a whole category of subtle bugs around time zones and precision.