How to make JavaScript time

Create custom time functions in JavaScript using Date objects and methods; example: get current time in ms.

JavaScript Date and Time

In JavaScript, the Date object is used to work with dates and times. It provides a number of built-in methods for formatting and managing dates and times. The Date object also helps in calculating dates, which is useful for scheduling and timing events.

The following example shows how to create and initialize a Date object in JavaScript:


// Create a new date object 
let date = new Date();

// Initialize the date object
date.setFullYear(2021, 0, 1);

The Date object has a wide range of methods that can be used to work with dates and times. For example, the getFullYear() method can be used to get the full year of a date:


// Get the full year of a date
let year = date.getFullYear();
// Output 2021
console.log(year); 

The Date object also has methods to get and set the month, day, hour, minute, and second of a date. For example, the getMonth() method can be used to get the month of a date:


// Get the month of a date
let month = date.getMonth();
// Output 0 (January)
console.log(month); 

The Date object has methods to add and subtract dates. For example, the setDate() method can be used to add a number of days to a date:


// Add 10 days to the date
date.setDate(date.getDate() + 10);

// Get the new date
let newDate = date.toISOString();
// Output 2021-01-11T00:00:00.000Z
console.log(newDate); 

The Date object also has methods to format dates and times. For example, the toDateString() method can be used to format a date as a string:


// Format the date as a string
let dateString = date.toDateString();
// Output Sun Jan 11 2021
console.log(dateString); 

The Date object can be used to work with dates and times in JavaScript. It provides a number of built-in methods for formatting and managing dates and times. It also provides methods to add and subtract dates, and to format dates and times as strings.

Answers (0)