Skip to content
-
How to Get the Current Date in JavaScript ?
Last Updated :
28 Oct, 2024
The Date() object is used to access the current date in JavaScript. To get the current date in string format, we can use toDateString() method. The date.toDateString() method converts the given date object into the date portion into a string.
Syntax
dateObj.toDateString()
JavaScript
// Create a Date Object
let d = new Date();
let d1 = d.toDateString();
console.log(d1);
Example: By default, the Date() constructor display the complete date as a string.
JavaScript
// Create a Date Object
let d = new Date();
console.log(d);
Output2024-10-28T07:56:14.317Z
Extracting Day, Month, and Year from Date Object
You can extract individual components of date like —day, month, and year from the Date object.
let d = new Date();
let date = d.getDate();
let d = new Date();
let month = String(d.getMonth() + 1).padStart(2, '0');
let d = new Date();
let year = d.getFullYear();
Example: Getting the current date (day, month, and year) from the date object.
JavaScript
let d = new Date();
let day = String(d.getDate()).padStart(2, "0");
let month = String(d.getMonth() + 1).padStart(2, "0");
let year = d.getFullYear();
let d1 = day + "/" + month + "/" + year;
console.log(d1);
We have a complete list of JavaScript Date Objects, to check those please go through this JavaScript Date Object Reference article.
Similar Reads
How to check if the given date is weekend ? To check if a given date falls on a weekend in JavaScript, you can use the getDay() method on a Date object. This method returns a number representing the day of the week, where 0 is Sunday and 6 is Saturday.There are two methods to solve this problem which are discussed below: Table of ContentUsing
2 min read
How to Convert Date to Another Timezone in JavaScript? Converting a date to another timezone in JavaScript means adjusting the local date and time to match the time in a different timezone. This ensures that the displayed time aligns with the selected timezone, often using built-in methods or external libraries.1. Using Intl.DateTimeFormat() and format(
2 min read
How to check if date is less than 1 hour ago using JavaScript ? Given a date and the task is to check whether the given date is less than 1 hour ago or not with the help of JavaScript. Approach 1: Count the milliseconds of the difference between the current and prev_date.If those are greater than milliseconds in 1 hour, then it returns false otherwise returns tr
2 min read
How to check a date is valid or not using JavaScript? To check if a date is valid or not in JavaScript, we have to know all the valid formats of the date. For ex - "YYYY/DD/MM", "DD/MM/YYYY", and "YYYY-MM-DD", etc. We have a given date format and we need to check whether the given format is valid or not according to the official and acceptable date for
3 min read
How to get the day and month of a year using JavaScript ? Given a date and the task is to get the day and month of a year using JavaScript. Approach: First get the current date by using new Date().Use getDay() method to get the current day in number format, Map it to the day name.Use getMonth() to get the current month in number format, Map it to the month
2 min read
How to calculate the date three months prior using JavaScript ? To calculate the date three months prior using JavaScript, we could use the getMonth() and setMonth() methods. In this article, we are going to learn how to calculate the date three months prior using JavaScript. ApproachFirst, select the date object.Then use the getMonth() method to get the months.
1 min read
How to calculate the yesterday's date in JavaScript ? In this article, we will see how to calculate yesterdayâs date in JavaScript. To calculate yesterday's date, you need to have some basic ideas of a few methods of JavaScript. JavaScript getDate() MethodJavaScript setDate() MethodJavaScript getDate() Method: It is an inbuilt JavaScript function that
3 min read
How to calculate minutes between two dates in JavaScript ? Given two dates and the task is to get the number of minutes between them using JavaScript. Approach: Initialize both Date object.Subtract the older date from the new date. It will give the number of milliseconds from 1 January 1970.Convert milliseconds to minutes. Example 1: This example uses the c
2 min read
How to get the first day of the year in JavaScript ? Given a date/year and the task is to get the first day of the year using JavaScript. Approach 1: Use getFullYear() Method to get the year from the given date.Use the new Date() function to create the new date object using year, month, and day. Example: This example uses the getFullYear() method to g
1 min read
How to remove time from date using JavaScript ? Given a Date Object and the task is to remove the time portion from the object using JavaScript. JavaScript split() Method: This method is used to split a string into an array of substrings, and returns the new array. Syntax: string.split( separator, limit ) Parameters: separator: This parameter is
2 min read
top_of_element && top_of_screen articleRecommendedTop && top_of_screen articleRecommendedBottom)) {
if (!isfollowingApiCall) {
isfollowingApiCall = true;
setTimeout(function(){
if (loginData && loginData.isLoggedIn) {
if (loginData.userName !== $('#followAuthor').val()) {
is_following();
} else {
$('.profileCard-profile-picture').css('background-color', '#E7E7E7');
}
} else {
$('.follow-btn').removeClass('hideIt');
}
}, 3000);
}
}
});
}
$(".accordion-header").click(function() {
var arrowIcon = $(this).find('.bottom-arrow-icon');
arrowIcon.toggleClass('rotate180');
});
});
window.isReportArticle = false;
function report_article(){
if (!loginData || !loginData.isLoggedIn) {
const loginModalButton = $('.login-modal-btn')
if (loginModalButton.length) {
loginModalButton.click();
}
return;
}
if(!window.isReportArticle){
//to add loader
$('.report-loader').addClass('spinner');
jQuery('#report_modal_content').load(gfgSiteUrl+'wp-content/themes/iconic-one/report-modal.php', {
PRACTICE_API_URL: practiceAPIURL,
PRACTICE_URL:practiceURL
},function(responseTxt, statusTxt, xhr){
if(statusTxt == "error"){
alert("Error: " + xhr.status + ": " + xhr.statusText);
}
});
}else{
window.scrollTo({ top: 0, behavior: 'smooth' });
$("#report_modal_content").show();
}
}
function closeShareModal() {
const shareOption = document.querySelector('[data-gfg-action="share-article"]');
shareOption.classList.remove("hover_share_menu");
let shareModal = document.querySelector(".hover__share-modal-container");
shareModal && shareModal.remove();
}
function openShareModal() {
closeShareModal(); // Remove existing modal if any
let shareModal = document.querySelector(".three_dot_dropdown_share");
shareModal.appendChild(Object.assign(document.createElement("div"), { className: "hover__share-modal-container" }));
document.querySelector(".hover__share-modal-container").append(
Object.assign(document.createElement('div'), { className: "share__modal" }),
);
document.querySelector(".share__modal").append(Object.assign(document.createElement('h1'), { className: "share__modal-heading" }, { textContent: "Share to" }));
const socialOptions = ["LinkedIn", "WhatsApp","Twitter", "Copy Link"];
socialOptions.forEach((socialOption) => {
const socialContainer = Object.assign(document.createElement('div'), { className: "social__container" });
const icon = Object.assign(document.createElement("div"), { className: `share__icon share__${socialOption.split(" ").join("")}-icon` });
const socialText = Object.assign(document.createElement("span"), { className: "share__option-text" }, { textContent: `${socialOption}` });
const shareLink = (socialOption === "Copy Link") ?
Object.assign(document.createElement('div'), { role: "button", className: "link-container CopyLink" }) :
Object.assign(document.createElement('a'), { className: "link-container" });
if (socialOption === "LinkedIn") {
shareLink.setAttribute('href', `https://www.linkedin.com/sharing/share-offsite/?url=${window.location.href}`);
shareLink.setAttribute('target', '_blank');
}
if (socialOption === "WhatsApp") {
shareLink.setAttribute('href', `https://api.whatsapp.com/send?text=${window.location.href}`);
shareLink.setAttribute('target', "_blank");
}
if (socialOption === "Twitter") {
shareLink.setAttribute('href', `https://twitter.com/intent/tweet?url=${window.location.href}`);
shareLink.setAttribute('target', "_blank");
}
shareLink.append(icon, socialText);
socialContainer.append(shareLink);
document.querySelector(".share__modal").appendChild(socialContainer);
//adding copy url functionality
if(socialOption === "Copy Link") {
shareLink.addEventListener("click", function() {
var tempInput = document.createElement("input");
tempInput.value = window.location.href;
document.body.appendChild(tempInput);
tempInput.select();
tempInput.setSelectionRange(0, 99999); // For mobile devices
document.execCommand('copy');
document.body.removeChild(tempInput);
this.querySelector(".share__option-text").textContent = "Copied"
})
}
});
// document.querySelector(".hover__share-modal-container").addEventListener("mouseover", () => document.querySelector('[data-gfg-action="share-article"]').classList.add("hover_share_menu"));
}
function toggleLikeElementVisibility(selector, show) {
document.querySelector(`.${selector}`).style.display = show ? "block" : "none";
}
function closeKebabMenu(){
document.getElementById("myDropdown").classList.toggle("show");
}