Date and Time Function
Date and time in JavaScript are primarily handled using the Date object. The Date object provides methods to retrieve and format dates in various formats.
The following table describes various JavaScript DateTime formats and their results.
Format | Result |
---|---|
new Date().toLocaleDateString(‘en-US’) | 05/29/2015 |
new Date().toLocaleDateString(‘en-GB’) | 29/05/2015 |
new Date().toLocaleString(‘en-US’, { weekday: ‘long’, year: ‘numeric’, month: ‘long’, day: ‘numeric’ }) | Friday, May 29, 2015 |
new Date().toLocaleString(‘en-US’, { weekday: ‘long’, year: ‘numeric’, month: ‘long’, day: ‘numeric’, hour: ‘numeric’, minute: ‘numeric’ }) | Friday, May 29, 2015, 5:50 AM |
new Date().toLocaleString(‘en-GB’, { weekday: ‘long’, year: ‘numeric’, month: ‘long’, day: ‘numeric’, hour: ‘numeric’, minute: ‘numeric’ }) | Friday, 29 May 2015, 05:50 |
new Date().toLocaleString(‘en-US’, { weekday: ‘long’, year: ‘numeric’, month: ‘long’, day: ‘numeric’, hour: ‘2-digit’, minute: ‘2-digit’, second: ‘2-digit’ }) | Friday, May 29, 2015, 05:50:06 AM |
new Date().toLocaleDateString(‘en-US’, { year: ‘numeric’, month: ‘2-digit’, day: ‘2-digit’ }) | 05/29/2015 |
new Date().toLocaleString(‘en-US’, { hour: ‘2-digit’, minute: ‘2-digit’ }) | 05:50 AM |
new Date().toLocaleTimeString(‘en-US’, { hour: ‘2-digit’, minute: ‘2-digit’ }) | 05:50 AM |
new Date().toLocaleString(‘en-US’, { hour: ‘numeric’, minute: ‘numeric’, second: ‘numeric’ }) | 5:50:06 AM |
new Date().toISOString() | 2015-05-16T05:50:06.719Z |
new Date().toLocaleString(‘en-US’, { weekday: ‘short’, month: ‘short’, day: ‘2-digit’, year: ‘numeric’, hour: ‘2-digit’, minute: ‘2-digit’, second: ‘2-digit’ }) | Fri, May 16, 2015, 05:50:06 AM |
Basic Structures:
Declaration without initialization:
let dateTimeVariable;
Declaration with initialization to a specific date and time:
let dateTimeVariable = new Date(year, month, day, hour, minute, second);
Declaration with initialization to the current date and time:
let currentDateTime = new Date();
Example
<body>
<script>
// Current Date and Time Example
let Default = new Date(); // Define the current date and time
let Custom = new Date().toLocaleString(‘en-US’, { month: ‘2-digit’, day: ‘2-digit’, year: ‘numeric’, hour: ‘2-digit’, minute: ‘2-digit’, hour12: true }); // Custom format
console.log(“Current Date and Time (Default): ” + Default);
console.log(“Current Date and Time (Custom): ” + Custom);
</script>
</body>
Code Explanation:
let Default = new Date(); // Define the current date and time
This line creates a new Date object, which gets the current date and time from the system and assigns it to the variable Default.
• new Date() returns a Date object representing the current date and time based on the system’s locale
settings and time zone.
let Custom = new Date().toLocaleString(‘en-US’, { month: ‘2-digit’, day: ‘2-digit’, year: ‘numeric’, hour: ‘2-digit’, minute: ‘2-digit’, hour12: true });
This line also creates a new Date object and formats it using the toLocaleString() method. The method converts the date into a string according to the specified options.
‘en-US’: Specifies that the date should be formatted using the US English locale.
The options object { month: ‘2-digit’, day: ‘2-digit’, year: ‘numeric’, hour: ‘2-digit’, minute: ‘2-digit’, hour12: true } specifies how the date should be displayed:
• month: ‘2-digit’: Month is displayed as two digits (e.g., 01, 02, …, 12).
• day: ‘2-digit’: Day of the month is displayed with two digits (e.g., 01, 02, …, 31).
• year: ‘numeric’: Full year is displayed (e.g., 2024).
• hour: ‘2-digit’: Hour in a 12-hour clock, displayed with two digits (e.g., 01, 02, …, 12).
• minute: ‘2-digit’: Minutes displayed with two digits (e.g., 01, 02, …, 59).
• hour12: true: This option specifies that the time should use the 12-hour clock (with AM/PM).
This results in a custom formatted date string that might look something like this: “12/25/2024, 05:30 PM”.
console.log(“Current Date and Time (Default): ” + Default);
This logs the Default date and time (created by new Date()) to the console.
The Default variable is a Date object, and when you log in, it gets automatically converted to a string, showing the date and time in the default format (e.g., “Wed Nov 21 2024 10:40:30 GMT+0000 (Coordinated Universal Time)”).
console.log(“Current Date and Time (Custom): ” + Custom);:
This logs the Custom formatted date and time to the console, which is formatted according to the options passed in toLocaleString(). For example, “11/21/2024, 10:40 AM”.
Output:
Common Date Methods:
- d: Day of the month (1–31)
- dd: Day of the month (01–31)
- ddd: Abbreviated weekday name (e.g., Mon, Tue, Wed)
- dddd: Full weekday name (e.g., Monday, Tuesday, Wednesday)
- h: Hour in 12-hour clock (1–12)
- hh: Hour in 12-hour clock with leading zero (01–12)
- H: Hour in 24-hour clock (0–23)
- HH: Hour in 24-hour clock with leading zero (00–23)
- m: Minutes (0–59)
- mm: Minutes with leading zero (00–59)
- M: Month number (1–12)
- MM: Month number with leading zero (01–12)
- MMM: Abbreviated month name (e.g., Jan, Feb, Mar)
- MMMM: Full month name (e.g., January, February, March)
- s: Seconds (0–59)
- ss: Seconds with leading zero (00–59)
- t: Abbreviated AM/PM (e.g., A or P)
- tt: Full AM/PM (e.g., AM or PM)
- y: Year (e.g., 15 for 2015)
- yy: Year with two digits (e.g., 15 for 2015)
- yyyy: Year with four digits (e.g., 2015)
- K: Time zone offset from UTC (e.g., +05:00)
- z: Time zone offset (e.g., +6)
- zz: Time zone offset with leading zero (e.g., +06)
- zzz: Time zone offset in hours and minutes (e.g., +06:00)
- f: Tenths of a second
- ff: Hundredths of a second
- fff: Milliseconds
- ffff: Ten-thousandths of a second
- fffff: Hundred-thousandths of a second
- ffffff: Millionths of a second
- fffffff: Ten-millionths of a second
Course Video
Examples for Practice
You have to solve all the questions given below in the editor without copy-pasting.
1. Write a function isLeapYear that takes a year as a parameter and returns true if it’s a leap year, otherwise false.
A leap year is a year that is divisible by 4, except for years that are divisible by 100 but not divisible by 400. The function checks these conditions and returns `true` if they are met, indicating it’s a leap year.
Here’s an example program:
function isLeapYear(year) {
return (year % 4 === 0 && year % 100 !== 0) || (year % 400 === 0);
}
let ans = isLeapYear(2024);
console.log(ans);
Output
2. Write a function getDaysInMonth that takes a month (1-12) and a year as parameters and returns the number of days in that month. Take into account leap years.
This function uses the Date object to get the last day of the given month. It then extracts the day component, giving the total number of days in that month.
Here’s an example program:
function getDaysInMonth(month, year) {
return new Date(year, month, 0).getDate();
}
const daysInFebruary2024 = getDaysInMonth(2, 2024);
console.log(daysInFebruary2024);
Output
3. Write a function getNextFriday that takes the current date as a parameter and returns the date of the next Friday.
The function calculates the difference between the current day and Friday. If the current day is before Friday, it calculates how many days are left until Friday. If the current day is Friday or later, it calculates how many days are left until the next Friday.
Here’s an example program:
function getNextFriday(currentDate) {
const dayOfWeek = currentDate.getDay();
const daysUntilFriday = dayOfWeek <= 5 ? 5 – dayOfWeek : 12 – dayOfWeek;
const nextFriday = new Date(currentDate);
nextFriday.setDate(currentDate.getDate() + daysUntilFriday);
return nextFriday;
}
const currentDate = new Date(); // Assuming the current date is today
const nextFriday = getNextFriday(currentDate);
console.log(nextFriday);
Output
4. Write a function isWeekend that takes a date as a parameter and returns true if it falls on a weekend (Saturday or Sunday), otherwise false.
The function uses the getDay method of the Date object, which returns the day of the week (0 for Sunday, 1 for Monday, …, 6 for Saturday). If the day is 0 (Sunday) or 6 (Saturday), it means the date falls on a weekend, and the function returns true. Otherwise, it returns false.
Here’s an example program:
function isWeekend(date) {
const day = date.getDay();
return day === 0 || day === 6; // 0 represents Sunday, 6 represents Saturday
}
const currentDate = new Date(); // Assuming the current date is today
const isWeekendToday = isWeekend(currentDate);
console.log(isWeekendToday);
Output