JS Date & Time Function

HTML
CSS
C#
SQL

Date and Time Function

The JavaScript Date object is used to work with dates and times. It provides various methods and properties to interact with dates, allowing you to retrieve and manipulate information such as the current date, and individual components (year, month, day, etc.), and perform various operations.

Creating a Date Object:

You can create a Date object in JavaScript in several ways:

1. Current Date and Time:

   let currentDate = new Date();
   console.log(“Current Date and Time: ” + currentDate);

2. Using a String (Date String Format):

   let dateString = new Date(“December 17, 2023 03:24:00”);
   console.log(“Date from String: ” + dateString);

3. Using Year, Month, Day, Hour, Minute, Second:

  let specificDate = new Date(2023, 11, 17, 3, 24, 0); // Note: Months are zero-based (0-11)
   console.log(“Specific Date: ” + specificDate);

Common Date Methods:

1. Current Date and Time:

   let date = new Date();
   let year = date.getFullYear();
   let month = date.getMonth() + 1; // Months are zero-based (0-11)
   let day = date.getDate();
   let hours = date.getHours();
   let minutes = date.getMinutes();
   let seconds = date.getSeconds();

   console.log(Year: ${year}, Month: ${month}, Day: ${day}, Hours: ${hours}, Minutes: ${minutes}, Seconds: ${seconds});

2. Formatting Dates:

  let date = new Date();
   let formattedDate = date.toLocaleDateString(‘en-US’, { weekday: ‘long’, year: ‘numeric’, month: ‘long’, day: ‘numeric’ });
   console.log(“Formatted Date: ” + formattedDate);

3. Date Arithmetic:

let now = new Date();
   let futureDate = new Date(now.getTime() + 7 * 24 * 60 * 60 * 1000); // Adding 7 days
   console.log(“Future Date: ” + futureDate);

Common Date Properties:

1. getTime():

   let date = new Date();
   let timestamp = date.getTime(); // Returns the timestamp (milliseconds since January 1, 1970)
   console.log(“Timestamp: ” + timestamp);

2. getDay():

   let date = new Date();
   let dayOfWeek = date.getDay(); // Returns the day of the week (0-6, where 0 is Sunday)
   console.log(“Day of Week: ” + dayOfWeek);

3. getMonth():

   let date = new Date();
   let month = date.getMonth(); // Returns the month (0-11)
   console.log(“Month: ” + month); 

4. getFullYear():

   let date = new Date();
   let year = date.getFullYear(); // Returns the year
   console.log(“Year: ” + year);

Working with Date and Time in JavaScript:

– JavaScript’s Date object is versatile and allows for a wide range of operations.
– The toLocaleDateString method is particularly useful for formatting dates based on the user’s locale.
– Date arithmetic involves manipulating the timestamp, which represents the number of milliseconds since January 1, 1970.

Here are the List of Javascript Date and Time Function:
 Function
Description
Example

new Date()

Creates a new Date object with the current date and time.

const now = new Date();

Date.parse()

Parses a date string and returns the number of milliseconds since January 1, 1970, 00:00:00 UTC.

const timestamp = Date.parse(“2023-03-09T15:30:00.000Z”);

Date.now()         

Returns the number of milliseconds since January 1, 1970, 00:00:00 UTC..

const timestamp = Date.now();

getFullYear()

Returns the year of the given date according to local time.

const year = now.getFullYear();

getMonth()

Returns the month of the given date according to local time, where January is 0 and December is 11.

const month = now.getMonth();

getDate()

Returns the day of the month of the given date according to local time.

const date = now.getDate();

 

getDay()              

Returns the day of the week of the given date according to local time, where Sunday is 0 and Saturday is 6.

const day = now.getDay();

getHours()

Returns the hour of the given date according to local time.

const hours = now.getHours();

getMinutes()

Returns the minutes of the given date according to local time.

const minutes = now.getMinutes();

getSeconds()

Returns the seconds of the given date according to local time.

const seconds = now.getSeconds();

getMilliseconds()

Returns the milliseconds of the given date according to local time.

const milliseconds = now.getMilliseconds();

getTime()

Returns the number of milliseconds since January 1, 1970, 00:00:00 UTC, represented by the given date.

const timestamp = now.getTime();

 

toLocaleDateString()

Returns a string that represents the given date according to the locale of the user.     

const dateStr = now.toLocaleDateString();

toLocaleTimeString()

Returns a string that represents the time of the given date according to the locale of the user.

const timeStr = now.toLocaleTimeString();

toDateString()

Returns a string that represents the date portion of the given date according to local time.          

const dateStr = now.toDateString();

toTimeString()

Returns a string that represents the time portion of the given date according to local time.

const timeStr = now.toTimeString();

toString()             

Returns a string that represents the given date according to local time.

const dateStr = now.toString();;

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