Reading Time 3
Number of Words 476
JavaScript provides powerful built-in global objects that simplify common programming tasks.
Two of the most essential are the Date and Math objects. These allow developers to efficiently manage dates, times, and perform mathematical operations without needing extra libraries.
Working with the Date Object
The Date object allows you to create, manipulate, and format dates and times. It's widely used for everything from timestamps to time calculations.
Creating Date Instances
You can create a new date object representing the current date and time:
const now = new Date(); console.log(now); // e.g., 2025-10-09T15:55:00.000Z
You can also create a date based on a specific timestamp or string:
const specificDate = new Date('2025-12-25T12:00:00'); console.log(specificDate);
Or use numeric parameters for year, month, day, etc. (Note: months are zero-indexed)
const customDate = new Date(2025, 11, 25, 12, 0, 0); // December 25, 2025 at noon console.log(customDate);
Extracting Date Components
You can get parts of a date easily:
const year = now.getFullYear(); // 2025 const month = now.getMonth() + 1; // Month (1-12) const day = now.getDate(); // Day of the month const hours = now.getHours(); // Hours (0-23) const minutes = now.getMinutes(); // Minutes (0-59) const seconds = now.getSeconds(); // Seconds (0-59) console.log(`Today is ${month}/${day}/${year} at ${hours}:${minutes}:${seconds}`);
Working with Timestamps and Durations
You can get the timestamp (milliseconds since Unix Epoch):
const timestamp = now.getTime(); console.log(timestamp);
You can calculate date differences to find durations:
const futureDate = new Date(2026, 0, 1); const durationMs = futureDate - now; const durationDays = Math.floor(durationMs / (1000 * 60 * 60 * 24)); console.log(`Days until 2026: ${durationDays}`);
Formatting Dates
While the Date object lacks robust built-in formatting options, you can format dates manually or use Intl.DateTimeFormat for locale-aware formatting:
const formatter = new Intl.DateTimeFormat('en-US', { year: 'numeric', month: 'long', day: 'numeric', hour: '2-digit', minute: '2-digit' }); console.log(formatter.format(now)); // e.g., October 9, 2025, 3:56 PM
Using the Math Object for Numbers and Calculations
The Math object offers many static methods and constants to perform mathematical operations.
Basic Math Operations
-
Find minimum and maximum:
console.log(Math.min(10, 25, 3, 7)); // 3 console.log(Math.max(10, 25, 3, 7)); // 25
-
Rounding numbers:
console.log(Math.round(4.7)); // 5 console.log(Math.floor(4.7)); // 4 console.log(Math.ceil(4.2)); // 5
-
Absolute value:
console.log(Math.abs(-10)); // 10
-
Power and square root:
console.log(Math.pow(3, 4)); // 81 (3 to the power 4) console.log(Math.sqrt(49)); // 7
Random Numbers
Generate a random floating-point number between 0 (inclusive) and 1 (exclusive):
console.log(Math.random());
Generate a random integer in a specified range (inclusive):
function getRandomInt(min, max) { return Math.floor(Math.random() * (max - min + 1)) + min; } console.log(getRandomInt(1, 100)); // Random number between 1 and 100
Trigonometry Functions
Math object also supports sine, cosine, tangent, useful for graphics and animations:
console.log(Math.sin(Math.PI / 2)); // 1 console.log(Math.cos(0)); // 1
Practical Example: Countdown Timer Using Date and Math
function countdown(dateString) {
const targetDate = new Date(dateString);
const now = new Date();
const diff = targetDate - now;
if (diff <= 0) {
return 'Time is up!';
}
const days = Math.floor(diff / (1000 * 60 * 60 * 24));
const hours = Math.floor((diff / (1000 * 60 * 60)) % 24);
const mins = Math.floor((diff / (1000 * 60)) % 60);
const secs = Math.floor((diff / 1000) % 60);
return `Countdown: ${days}d ${hours}h ${mins}m ${secs}s`;
}
console.log(countdown('2025-12-31T23:59:59'));