-
Hajipur, Bihar, 844101
Hajipur, Bihar, 844101
JS Basics
JS Variables & Operators
JS Data Types & Conversion
JS Numbers & Math
JS Strings
JS Dates
JS Arrays
JS Control Flow
JS Loops & Iteration
JS Functions
JS Functions
Function Definitions
Function Parameters
Function Invocation
Function Call
Function Apply
Function Bind
Function Closures
JS Arrow Function
JS Objects
JS Objects
JS Object Properties
JS Object Methods
JS Object Display
JS Object Constructors
Object Definitions
Object Get / Set
Object Prototypes
Object Protection
JS Classes & Modules
JS Async Programming
JS Advanced
JS Destructuring
JS Bitwise
JS RegExp
JS Precedence
JS Errors
JS Scope
JS Hoisting
JS Strict Mode
JS this Keyword
JS HTML DOM
DOM Intro
DOM Methods
DOM Document
DOM Elements
DOM HTML
DOM Forms
DOM CSS
DOM Animations
DOM Events
DOM Event Listener
DOM Navigation
DOM Nodes
DOM Collections
DOM Node Lists
JS BOM (Browser Object Model)
JS Web APIs
Web API Intro
Web Validation API
Web History API
Web Storage API
Web Worker API
Web Fetch API
Web Geolocation API
JS AJAX
AJAX Intro
AJAX XMLHttp
AJAX Request
AJAX Response
AJAX XML File
AJAX PHP
AJAX ASP
AJAX Database
AJAX Applications
AJAX Examples
JS JSON
JSON Intro
JSON Syntax
JSON vs XML
JSON Data Types
JSON Parse
JSON Stringify
JSON Objects
JSON Arrays
JSON Server
JSON PHP
JSON HTML
JSON JSONP
JS Graphics & Charts
Working with dates and times is an essential aspect of web development. Whether you are building a calendar, scheduling events, calculating durations, generating reports, or tracking user activity, accurate date handling is crucial. JavaScript provides the built-in Date object, which allows developers to create, manipulate, format, and calculate dates and times with precision.
In this tutorial, you will learn how the Date object works, how to create and manipulate dates, practical examples, common mistakes, best practices, and real-world applications. By the end, you will have a solid understanding of managing dates in JavaScript efficiently.
The Date object represents a specific point in time and internally stores the number of milliseconds since January 1, 1970, 00:00:00 UTC, known as the "epoch." This object provides a range of methods to retrieve, modify, and format date and time values. Using Date, developers can perform operations such as calculating the difference between dates, adding or subtracting time, and converting dates to user-friendly formats.
Creating a Date instance is done using the new Date() constructor:
let currentDate = new Date();
console.log(currentDate);
This outputs the current date and time according to the system's clock.
Dates are fundamental in many scenarios:
Displaying timestamps in dashboards, websites, and logs
Scheduling events, meetings, or reminders
Tracking user activity or login times
Calculating ages, deadlines, or subscription durations
Generating reports based on time intervals
Handling time zones for users across the world
Accurate date handling ensures reliability, improves user experience, and prevents errors related to time calculations.
JavaScript provides multiple ways to create date instances.
let now = new Date();
console.log(now);
This creates a Date object representing the exact current date and time.
You can pass a date string to create a specific date:
let birthday = new Date("2003-07-10");
console.log(birthday);
Using the ISO format (YYYY-MM-DD) is recommended for consistent results across browsers.
let meeting = new Date(2025, 11, 25, 10, 30, 0); // December 25, 2025, 10:30:00
console.log(meeting);
Note: Months are zero-based. January is 0, February is 1, and December is 11.
let epochTime = new Date(1672531200000);
console.log(epochTime);
This creates a date based on milliseconds elapsed since January 1, 1970.
The Date object provides methods to access specific parts of a date:
let today = new Date();
console.log(today.getFullYear()); // Year
console.log(today.getMonth()); // Month (0-11)
console.log(today.getDate()); // Day of the month (1-31)
console.log(today.getDay()); // Day of the week (0-6)
console.log(today.getHours()); // Hours (0-23)
console.log(today.getMinutes()); // Minutes (0-59)
console.log(today.getSeconds()); // Seconds (0-59)
console.log(today.getMilliseconds()); // Milliseconds (0-999)
You can modify dates using set methods or by performing calculations.
let event = new Date();
event.setFullYear(2026);
event.setMonth(5); // June
event.setDate(15);
event.setHours(14);
event.setMinutes(30);
console.log(event);
let reminder = new Date();
reminder.setDate(reminder.getDate() + 7); // 7 days from now
console.log(`Reminder set for: ${reminder}`);
let now = new Date();
console.log(`Current Date and Time: ${now.toString()}`);
let birthDate = new Date("2003-07-10");
let today = new Date();
let age = today.getFullYear() - birthDate.getFullYear();
let monthDiff = today.getMonth() - birthDate.getMonth();
if (monthDiff < 0 || (monthDiff === 0 && today.getDate() < birthDate.getDate())) {
age--;
}
console.log(`Age: ${age} years`);
let eventDate = new Date("2025-12-31");
let today = new Date();
let remainingDays = Math.ceil((eventDate - today) / (1000 * 60 * 60 * 24));
console.log(`Days until event: ${remainingDays}`);
let birthday = new Date("2002-05-15");
console.log(`Happy Birthday! Your birthday is on ${birthday.toDateString()}`);
let reminder = new Date();
for (let i = 1; i <= 4; i++) {
let nextReminder = new Date(reminder);
nextReminder.setDate(reminder.getDate() + i * 7);
console.log(`Week ${i} reminder: ${nextReminder.toDateString()}`);
}
let startDate = new Date("2025-01-01");
let endDate = new Date("2025-12-31");
let difference = endDate - startDate;
let days = difference / (1000 * 60 * 60 * 24);
console.log(`Total days in the year: ${days}`);
Forgetting that months are zero-based
Ignoring time zones when comparing dates
Using inconsistent date string formats
Performing arithmetic on Date objects without converting to milliseconds
Not validating user-provided dates
Use ISO format (YYYY-MM-DD) for string-based dates
Consider libraries like dayjs or luxon for time zone handling
Convert dates to milliseconds for calculations
Use toDateString(), toTimeString(), or toLocaleString() for readable output
Validate user input when creating dynamic dates
The Date object is commonly used in:
Calendar and scheduling applications
E-commerce order and delivery tracking
Logs and activity monitoring
Reminders and notifications
Reports, analytics, and dashboards
Subscription and expiration management
The JavaScript Date object allows developers to manage dates and times effectively. It provides methods for creating, retrieving, manipulating, and formatting dates for a wide range of applications. By following best practices and avoiding common mistakes, you can handle time-based data accurately, making your web applications reliable, user-friendly, and functional across all scenarios.
Q1. How do you create a date object for July 10, 2025, using the Date constructor?
Q2. How do you get the current year from a Date object?
Q3. Which method returns the name of the day as a number (0 for Sunday to 6 for Saturday)?
Q4. How do you convert a Date object into a human-readable string like "Thu Jul 10 2025"?
Q5. What does the getMonth() method return for the month of December?
Q6. How do you change the year of an existing Date object to 2035?
Q7. Which method gives the time portion (HH:MM:SS) of a Date object?
Q8. How do you get today’s date in a localized format for your system?
Q9. What does new Date().toISOString() return?
Q10. How can you create a date object that includes time as well: July 10, 2025, 15:30?
JS Basics
JS Variables & Operators
JS Data Types & Conversion
JS Numbers & Math
JS Strings
JS Dates
JS Arrays
JS Control Flow
JS Loops & Iteration
JS Functions
JS Functions
Function Definitions
Function Parameters
Function Invocation
Function Call
Function Apply
Function Bind
Function Closures
JS Arrow Function
JS Objects
JS Objects
JS Object Properties
JS Object Methods
JS Object Display
JS Object Constructors
Object Definitions
Object Get / Set
Object Prototypes
Object Protection
JS Classes & Modules
JS Async Programming
JS Advanced
JS Destructuring
JS Bitwise
JS RegExp
JS Precedence
JS Errors
JS Scope
JS Hoisting
JS Strict Mode
JS this Keyword
JS HTML DOM
DOM Intro
DOM Methods
DOM Document
DOM Elements
DOM HTML
DOM Forms
DOM CSS
DOM Animations
DOM Events
DOM Event Listener
DOM Navigation
DOM Nodes
DOM Collections
DOM Node Lists
JS BOM (Browser Object Model)
JS Web APIs
Web API Intro
Web Validation API
Web History API
Web Storage API
Web Worker API
Web Fetch API
Web Geolocation API
JS AJAX
AJAX Intro
AJAX XMLHttp
AJAX Request
AJAX Response
AJAX XML File
AJAX PHP
AJAX ASP
AJAX Database
AJAX Applications
AJAX Examples
JS JSON
JSON Intro
JSON Syntax
JSON vs XML
JSON Data Types
JSON Parse
JSON Stringify
JSON Objects
JSON Arrays
JSON Server
JSON PHP
JSON HTML
JSON JSONP
JS Graphics & Charts
