Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • GfG 160: Daily DSA
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • JS Tutorial
  • JS Exercise
  • JS Interview Questions
  • JS Array
  • JS String
  • JS Object
  • JS Operator
  • JS Date
  • JS Error
  • JS Projects
  • JS Set
  • JS Map
  • JS RegExp
  • JS Math
  • JS Number
  • JS Boolean
  • JS Examples
  • JS Free JS Course
  • JS A to Z Guide
  • JS Formatter
Open In App
Next Article:
JavaScript Date Objects
Next article icon

JavaScript Date Objects

Last Updated : 12 Feb, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

In JavaScript, the Date object is a built-in object that allows you to work with dates and times. It provides a variety of methods to handle dates, compare them, manipulate them, and format them.

The Date object in JavaScript represents a single point in time. It provides various functionalities to work with dates and times like creating a Date object in several ways, and it allows you to perform operations like extracting parts of the date (year, month, day), comparing dates, and manipulating dates.

Creating a Date Object

You can create a Date object in multiple ways. Below are some of the most common methods:

1. Using the Default Date() Constructor

The default constructor creates a Date object representing the current date and time.

JavaScript
const now = new Date();
console.log(now);

Output
2025-01-16T04:25:58.204Z
  • new Date() creates a Date object for the current date and time.
  • console.log(now) prints the current date and time to the console.

2. Using a specific date string

You can pass a date string to the constructor to create a Date object for a specific date and time.

JavaScript
const specificDate = new Date("2023-12-25T10:00:00");
console.log(specificDate); 

Output
2023-12-25T10:00:00.000Z
  • new Date("2023-12-25T10:00:00") creates a date for December 25, 2023, at 10:00 AM.
  • console.log(specificDate) shows the date and time: "2023-12-25T10:00:00".

3. Using Year, Month, and Other Parameters

The Date constructor can also take individual parameters for year, month (0-indexed), day, hour, minute, second, and millisecond.

JavaScript
const anotherDate = new Date(2023, 11, 25, 10, 0, 0);
console.log(anotherDate);

Output
2023-12-25T10:00:00.000Z
  • new Date(2023, 11, 25, 10, 0, 0) creates a Date object for December 25, 2023, at 10:00 AM (months are 0-indexed, so 11 represents December).
  • console.log(anotherDate) outputs the specified date and time: "2023-12-25T10:00:00.000".

4. Using Timestamps

You can create a Date object from a timestamp (milliseconds since January 1, 1970).

JavaScript
const timestampDate = new Date(1672531200000);
console.log(timestampDate);

Output
2023-01-01T00:00:00.000Z
  • new Date(1672531200000) creates a Date object based on the number of milliseconds since January 1, 1970 (Unix Epoch).
  • console.log(timestampDate) outputs the corresponding date and time for that timestamp, which is "2023-01-01T00:00:00.000Z".

Getting Date and Time Components

Once you have a Date object, you can easily extract various components like the year, month, day, hours, minutes, and seconds.

JavaScript
let cDate = new Date();
console.log(cDate.getFullYear()); // Gets the current year
console.log(cDate.getMonth());  // Gets the current month (0-indexed)
console.log(cDate.getDate());   // Gets the current day of the month
console.log(cDate.getHours());  // Gets the current hour
console.log(cDate.getMinutes()); // Gets the current minutes
console.log(cDate.getSeconds()); // Gets the current seconds

Output
2025
1
11
18
34
9

Note: The getMonth() method returns a zero-indexed value (0 for January, 11 for December).

Date Manipulation

You can perform various date manipulations such as adding or subtracting days, months, or years to/from a specific date.

Adding Days to a Date

JavaScript
let cDate = new Date();
cDate.setDate(cDate.getDate() + 5); // Adds 5 days to the current date
console.log(cDate);

Output
2025-02-16T18:36:36.850Z

In this example, we use the setDate() method to add 5 days to the current date.

Comparing Dates

JavaScript also allows you to compare two Date objects to check if they are equal or which one is earlier or later.

JavaScript
let date1 = new Date('2023-12-31');
let date2 = new Date('2024-01-01');
if (date1 < date2) {
    console.log('date1 is earlier than date2');
} else if (date1 > date2) {
    console.log('date1 is later than date2');
} else {
    console.log('Both dates are the same');
}

Output
date1 is earlier than date2

In this example, we compare date1 and date2 using comparison operators like <, >, and ===.

Formatting Dates

JavaScript provides various methods to format dates into a human-readable string, although formatting options can be limited in plain JavaScript. You can use toLocaleDateString() or toLocaleTimeString() to format dates and times.

Formatting a Date to a Local String

JavaScript
let now = new Date();
let formattedDate = now.toLocaleDateString('en-US');
console.log(formattedDate);  // Output format: MM/DD/YYYY

Output
2/11/2025

The toLocaleDateString() method allows you to specify a locale (e.g., 'en-US' for American English) and formats the date accordingly.

Formatting Date and Time

JavaScript
let now = new Date();
let formattedDateTime = now.toLocaleString('en-US');
console.log(formattedDateTime);  // Output format: MM/DD/YYYY, HH:MM:SS AM/PM

Output
2/11/2025, 6:41:41 PM

The toLocaleString() method returns both the date and time in a localized format.

UTC Methods

In JavaScript, Date objects are based on the local time zone. However, you can use the UTC methods to handle date and time in Coordinated Universal Time (UTC).

JavaScript
let now = new Date();
console.log(now.getUTCFullYear()); // Gets the current year in UTC
console.log(now.getUTCMonth());  // Gets the current month (0-indexed) in UTC
console.log(now.getUTCDate());   // Gets the current day of the month in UTC

Output
2025
1
11

The getUTC*() methods return the corresponding date components in UTC.

Date Parsing

JavaScript's Date object allows you to parse date strings into Date objects.

JavaScript
let dateS = '2023-12-31';
let parsed = new Date(dateS);
console.log(parsed);

Output
2023-12-31T00:00:00.000Z

You can also parse date strings in various formats such as 'YYYY-MM-DD', 'MM/DD/YYYY', or even ISO 8601 date strings.

Date Object Method's Table

Here are some methods that define the usage of a Date object, These are non-static methods.

Below methods are returns all the values according to local time

MethodDescription
Date()It returns presents day’s date and time.
getDate()It returns the day for the specified date.
getDay()It returns the day of the week for the specified date.
getFullYear()It returns the year of the specified date.
getYear()This method returns the year in the specified date.
getHours()It returns the hour in a specified date.
getMilliseconds()It returns the milliseconds in the specified date.
getMinutes()It returns the minutes in the specified date.
getMonth()It returns the month in the specified date. This also find the month.
getSeconds()This method returns the seconds in the specified date.
getTime()This method returns the date in terms of numeric value as milliseconds.
setDate()This method sets the day of the month for a specified date.
setFullYear()This method sets the full year for a specified date.

Below methods are returns all the values according to universal time

MethodsDescription
getUTCDate()It returns the day of a month for a specified date.
getUTCDay()It returns the day of the week for a specified date.
getUTCFullYear()This method returns the year for a specified date.
getUTCHours()It returns the hours in a specified date.
getUTCMilliseconds()This method returns the milliseconds form for a specified date.
getUTCMinutes()This method returns the minutes in a specified date.
getUTCMonth()This method returns the month for a specified date.

Conclusion

The JavaScript Date object is a powerful tool for working with dates and times. By understanding its methods and properties, you can handle a wide variety of date-related tasks in your applications. For more advanced date manipulation and formatting, consider using external libraries to complement the built-in functionality.


Next Article
JavaScript Date Objects

S

SoumikMondal
Improve
Article Tags :
  • Technical Scripter
  • JavaScript
  • Web Technologies
  • javascript-date

Similar Reads

    JavaScript Get Date Methods
    JavaScript Date Object allows us to get and set the date values. In this article, we will know how to get the various date methods from the date object in Javascript. There are various methods that retrieve the date in JavaScript. The date values can get like years, months, days, hours, minutes, sec
    3 min read
    JavaScript Date Reference
    The JavaScript Date object is important for handling dates and times in web development. It provides various methods to create, manipulate, and format dates. Understanding the Date object and its methods allows you to work effectively with dates and times in your applications. This guide covers the
    4 min read
    JavaScript Date UTC() Method
    In JavaScript, the Date.UTC() method is used to create a date object representing a specified date and time in UTC (Coordinated Universal Time). It accepts the year, month, day, hour, minute, second, and millisecond components of the date and returns the number of milliseconds since January 1, 1970,
    4 min read
    JavaScript Date toString() Method
    JavaScript date.toString() method is used to convert the given date object's contents into a string. The date object is created using the date() constructor. Syntax:dateObj.toString();Parameters:This method does not accept any parameter. It is just used along with a Date object created using the Dat
    3 min read
    JavaScript Date toDateString() Method
    The date.toDateString() method converts the given date object’s contents of the date portion into a string. The date object is created using the date() constructor. Syntax: dateObj.toDateString() Parameters: This method does not accept any parameter. It is just used with a Date object created using
    4 min read
    JavaScript Date setUTCFullYear() Method
    The date.setUTCFullYear() method is used to set year into a date object according to universal time which is created using date() constructor. Syntax: DateObj.setUTCFullYear(year_Value); Parameter: This method accepts a single parameter as mentioned above and described below: year_Value: This parame
    3 min read
    JavaScript Date() Constructor
    JavaScript Date constructor is used to create a new Date object. The value returned will be different on the basis of whether the object is called with or without the new keyword. If we call the object new keyword a Date object is created otherwise a string representing the current dat-time is retur
    3 min read
    JavaScript Date Programming Examples
    The JavaScript comes with a built-in datatype called the Date object. The Date object is created by using a new keyword, i.e. new Date() . The Date object can be used for date and time in terms of millisecond precision within 100 million days before or after 1/1/1970. JavaScript Date Programming Exa
    5 min read
    New Date-Time API in Java 8
    New date-time API is introduced in Java 8 to overcome the following drawbacks of old date-time API : Not thread safe : Unlike old java.util.Date which is not thread safe the new date-time API is immutable and doesn't have setter methods.Less operations : In old API there are only few date operations
    6 min read
    ES6 Date
    The ES6 Date is defined as the number of milliseconds that have been passed since midnight on January 1, 1970, UTC. Date objects can be created by the new Date() constructor. In JavaScript, both date and time are represented by the Date object. Javascript Date Constructors: In JavaScript, a construc
    8 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

'); // $('.spinner-loading-overlay').show(); let script = document.createElement('script'); script.src = 'https://assets.geeksforgeeks.org/v2/editor-prod/static/js/bundle.min.js'; script.defer = true document.head.appendChild(script); script.onload = function() { suggestionModalEditor() //to add editor in suggestion modal if(loginData && loginData.premiumConsent){ personalNoteEditor() //to load editor in personal note } } script.onerror = function() { if($('.editorError').length){ $('.editorError').remove(); } var messageDiv = $('
').text('Editor not loaded due to some issues'); $('#suggestion-section-textarea').append(messageDiv); $('.suggest-bottom-btn').hide(); $('.suggestion-section').hide(); editorLoaded = false; } }); //suggestion modal editor function suggestionModalEditor(){ // editor params const params = { data: undefined, plugins: ["BOLD", "ITALIC", "UNDERLINE", "PREBLOCK"], } // loading editor try { suggestEditorInstance = new GFGEditorWrapper("suggestion-section-textarea", params, { appNode: true }) suggestEditorInstance._createEditor("") $('.spinner-loading-overlay:eq(0)').remove(); editorLoaded = true; } catch (error) { $('.spinner-loading-overlay:eq(0)').remove(); editorLoaded = false; } } //personal note editor function personalNoteEditor(){ // editor params const params = { data: undefined, plugins: ["UNDO", "REDO", "BOLD", "ITALIC", "NUMBERED_LIST", "BULLET_LIST", "TEXTALIGNMENTDROPDOWN"], placeholderText: "Description to be......", } // loading editor try { let notesEditorInstance = new GFGEditorWrapper("pn-editor", params, { appNode: true }) notesEditorInstance._createEditor(loginData&&loginData.user_personal_note?loginData.user_personal_note:"") $('.spinner-loading-overlay:eq(0)').remove(); editorLoaded = true; } catch (error) { $('.spinner-loading-overlay:eq(0)').remove(); editorLoaded = false; } } var lockedCasesHtml = `You can suggest the changes for now and it will be under 'My Suggestions' Tab on Write.

You will be notified via email once the article is available for improvement. Thank you for your valuable feedback!`; var badgesRequiredHtml = `It seems that you do not meet the eligibility criteria to create improvements for this article, as only users who have earned specific badges are permitted to do so.

However, you can still create improvements through the Pick for Improvement section.`; jQuery('.improve-header-sec-child').on('click', function(){ jQuery('.improve-modal--overlay').hide(); $('.improve-modal--suggestion').hide(); jQuery('#suggestion-modal-alert').hide(); }); $('.suggest-change_wrapper, .locked-status--impove-modal .improve-bottom-btn').on('click',function(){ // when suggest changes option is clicked $('.ContentEditable__root').text(""); $('.suggest-bottom-btn').html("Suggest changes"); $('.thank-you-message').css("display","none"); $('.improve-modal--improvement').hide(); $('.improve-modal--suggestion').show(); $('#suggestion-section-textarea').show(); jQuery('#suggestion-modal-alert').hide(); if(suggestEditorInstance !== null){ suggestEditorInstance.setEditorValue(""); } $('.suggestion-section').css('display', 'block'); jQuery('.suggest-bottom-btn').css("display","block"); }); $('.create-improvement_wrapper').on('click',function(){ // when create improvement option clicked then improvement reason will be shown if(loginData && loginData.isLoggedIn) { $('body').append('
'); $('.spinner-loading-overlay').show(); jQuery.ajax({ url: writeApiUrl + 'create-improvement-post/?v=1', type: "POST", contentType: 'application/json; charset=utf-8', dataType: 'json', xhrFields: { withCredentials: true }, data: JSON.stringify({ gfg_id: post_id }), success:function(result) { $('.spinner-loading-overlay:eq(0)').remove(); $('.improve-modal--overlay').hide(); $('.unlocked-status--improve-modal-content').css("display","none"); $('.create-improvement-redirection-to-write').attr('href',writeUrl + 'improve-post/' + `${result.id}` + '/', '_blank'); $('.create-improvement-redirection-to-write')[0].click(); }, error:function(e) { showErrorMessage(e.responseJSON,e.status) }, }); } else { if(loginData && !loginData.isLoggedIn) { $('.improve-modal--overlay').hide(); if ($('.header-main__wrapper').find('.header-main__signup.login-modal-btn').length) { $('.header-main__wrapper').find('.header-main__signup.login-modal-btn').click(); } return; } } }); $('.left-arrow-icon_wrapper').on('click',function(){ if($('.improve-modal--suggestion').is(":visible")) $('.improve-modal--suggestion').hide(); else{ } $('.improve-modal--improvement').show(); }); const showErrorMessage = (result,statusCode) => { if(!result) return; $('.spinner-loading-overlay:eq(0)').remove(); if(statusCode == 403) { $('.improve-modal--improve-content.error-message').html(result.message); jQuery('.improve-modal--overlay').show(); jQuery('.improve-modal--improvement').show(); $('.locked-status--impove-modal').css("display","block"); $('.unlocked-status--improve-modal-content').css("display","none"); $('.improve-modal--improvement').attr("status","locked"); return; } } function suggestionCall() { var editorValue = suggestEditorInstance.getValue(); var suggest_val = $(".ContentEditable__root").find("[data-lexical-text='true']").map(function() { return $(this).text().trim(); }).get().join(' '); suggest_val = suggest_val.replace(/\s+/g, ' ').trim(); var array_String= suggest_val.split(" ") //array of words var gCaptchaToken = $("#g-recaptcha-response-suggestion-form").val(); var error_msg = false; if(suggest_val != "" && array_String.length >=4){ if(editorValue.length { jQuery('.ContentEditable__root').focus(); jQuery('#suggestion-modal-alert').hide(); }, 3000); } } document.querySelector('.suggest-bottom-btn').addEventListener('click', function(){ jQuery('body').append('
'); jQuery('.spinner-loading-overlay').show(); if(loginData && loginData.isLoggedIn) { suggestionCall(); return; } // script for grecaptcha loaded in loginmodal.html and call function to set the token setGoogleRecaptcha(); }); $('.improvement-bottom-btn.create-improvement-btn').click(function() { //create improvement button is clicked $('body').append('
'); $('.spinner-loading-overlay').show(); // send this option via create-improvement-post api jQuery.ajax({ url: writeApiUrl + 'create-improvement-post/?v=1', type: "POST", contentType: 'application/json; charset=utf-8', dataType: 'json', xhrFields: { withCredentials: true }, data: JSON.stringify({ gfg_id: post_id }), success:function(result) { $('.spinner-loading-overlay:eq(0)').remove(); $('.improve-modal--overlay').hide(); $('.create-improvement-redirection-to-write').attr('href',writeUrl + 'improve-post/' + `${result.id}` + '/', '_blank'); $('.create-improvement-redirection-to-write')[0].click(); }, error:function(e) { showErrorMessage(e.responseJSON,e.status); }, }); });
"For an ad-free experience and exclusive features, subscribe to our Premium Plan!"
Continue without supporting
`; $('body').append(adBlockerModal); $('body').addClass('body-for-ad-blocker'); const modal = document.getElementById("adBlockerModal"); modal.style.display = "block"; } function handleAdBlockerClick(type){ if(type == 'disabled'){ window.location.reload(); } else if(type == 'info'){ document.getElementById("ad-blocker-div").style.display = "none"; document.getElementById("ad-blocker-info-div").style.display = "flex"; handleAdBlockerIconClick(0); } } var lastSelected= null; //Mapping of name and video URL with the index. const adBlockerVideoMap = [ ['Ad Block Plus','https://media.geeksforgeeks.org/auth-dashboard-uploads/abp-blocker-min.mp4'], ['Ad Block','https://media.geeksforgeeks.org/auth-dashboard-uploads/Ad-block-min.mp4'], ['uBlock Origin','https://media.geeksforgeeks.org/auth-dashboard-uploads/ub-blocke-min.mp4'], ['uBlock','https://media.geeksforgeeks.org/auth-dashboard-uploads/U-blocker-min.mp4'], ] function handleAdBlockerIconClick(currSelected){ const videocontainer = document.getElementById('ad-blocker-info-div-gif'); const videosource = document.getElementById('ad-blocker-info-div-gif-src'); if(lastSelected != null){ document.getElementById("ad-blocker-info-div-icons-"+lastSelected).style.backgroundColor = "white"; document.getElementById("ad-blocker-info-div-icons-"+lastSelected).style.borderColor = "#D6D6D6"; } document.getElementById("ad-blocker-info-div-icons-"+currSelected).style.backgroundColor = "#D9D9D9"; document.getElementById("ad-blocker-info-div-icons-"+currSelected).style.borderColor = "#848484"; document.getElementById('ad-blocker-info-div-name-span').innerHTML = adBlockerVideoMap[currSelected][0] videocontainer.pause(); videosource.setAttribute('src', adBlockerVideoMap[currSelected][1]); videocontainer.load(); videocontainer.play(); lastSelected = currSelected; }

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences