Date time Method in JavaScript
Date time Method in JavaScript
JavaScript provides a robust set of built-in Date methods to handle date and time operations efficiently. Whether you need to retrieve the current date, format time, or manipulate timestamps, JavaScript’s Date
object makes it simple. In this guide, we will explore various Date methods along with examples.
Before using Date methods, you need to create a Date
object in JavaScript.
var d = new Date();
console.log(d); // Outputs current date and time
Below is a list of essential Date methods in JavaScript:
getDate()
- Get the Day of the MonthReturns the numeric day of the month (1-31).
var d = new Date();
console.log(d.getDate()); // Outputs current day of the month
getDay()
- Get the Day of the WeekReturns the day of the week as a number (0 for Sunday, 6 for Saturday).
console.log(d.getDay()); // Outputs a number from 0 to 6
getFullYear()
- Get the YearReturns the four-digit year.
console.log(d.getFullYear()); // Outputs current year
getMonth()
- Get the MonthReturns the month as a number (0 for January, 11 for December).
console.log(d.getMonth()); // Outputs a number from 0 to 11
getHours()
- Get the HourReturns the hour (0-23) in a 24-hour format.
console.log(d.getHours()); // Outputs current hour
getMinutes()
- Get the MinutesReturns the minutes (0-59).
console.log(d.getMinutes()); // Outputs current minutes
getSeconds()
- Get the SecondsReturns the seconds (0-59).
console.log(d.getSeconds()); // Outputs current seconds
toString()
- Convert Date Object to StringReturns a string representation of the Date object.
console.log(d.toString());
// Example output: Mon Mar 07 2025 12:30:59 GMT+0530 (India Standard Time)
toDateString()
- Get Date as StringReturns the date portion in a readable format.
console.log(d.toDateString());
// Example output: Mon Mar 07 2025
toTimeString()
- Get Time as StringReturns the time portion of a Date object.
console.log(d.toTimeString());
// Example output: 12:33:39 GMT+0530 (India Standard Time)
JavaScript's Date object offers powerful methods to handle and manipulate dates and times. Whether you're working on a calendar, timestamping an event, or logging user activities, mastering these Date methods will enhance your JavaScript programming skills.
For more JavaScript tutorials and updates, follow us on [Instagram] and [Facebook]. 🚀