SoFunction
Updated on 2025-04-03

Detailed explanation of the time and date function new Date in JavaScript (5 functions to obtain timestamps)

Introduction:

The new Date() method in JavaScript is used to create a new Date object that represents the current date and time. The Date object provides many methods and properties that can be used to obtain and set date and time information.

new Date([year, month, day, hour, minute, second, millisecond])

Among them, each parameter is optional. If no parameters are specified, the new Date() method creates a Date object representing the current date and time.

1. About the new Date() function;

    First create a representative of the current time Date Object
    var nowTime = new Date();

    (nowTime);
    Console output Fri Nov 17 2023 10:41:58 GMT+0800 (China Standard Time)


    //Get Date Current time Year Month Day Time Minutes Time Minutes Seconds    (());
    //Console output 2023/11/17 10:41:58
    //Get Date Current time Year Month Day    (());
    //Console output 2023/11/17
    //Get Date Current Time Time Time Minutes Seconds    (());
    //Console output 10:41:58
    //Get the year of the Date object    (());
    //Console output 2023
    //Get the month of the Date object (note that the month starts from 0, so you need to add 1 when using it)    (());
    //Console output 11
    //Get the date of the Date object    (());
    //Console output 17
    //Get the hours of the Date object    (());
    //Console output 10
    // Get the minutes of the Date object    (());
    //Console output 41
    //Get the seconds of the Date object    (());
    //Console output 58
    //Get the milliseconds of the Date object    (());
    //Console output 917

2. Five ways to obtain the timestamp of the Date object;

    1、new Date().getTime()method
    const timestamp1 = new Date().getTime();
    (timestamp1);
    //Console output 1700189060045
    2、()method
    const timestamp2 = ();
    (timestamp2);
    //Console output 1700189060045
    3、(new Date())method
    const timestamp3 = (new Date());
    (timestamp3);
    //Console output 1700189060045
    4、new Date()).valueOf()method
    const timestamp4 = new Date().valueOf();
    (timestamp4);
    //Console output 1700189060045
    5、Number(new Date())method
    const timestamp5 = Number(new Date());
    (timestamp5);
    //Console output 1700189060045

3. Date object application example

Example 1: Calculate the month difference

sometimes,We need to know how many days there is between two dates。
You can convert dates to milliseconds first,Then subtract and divide by the milliseconds of one day(1000 * 60 * 60 * 24)Come to get the results。

function daysBetween(date1, date2) {
  let oneDay = 1000 * 60 * 60 * 24;
  return ((date2 - date1) / oneDay);
}

let start = new Date('June 20, 2022');
let end = new Date('July 20, 2022');

(daysBetween(start, end)); // Output "30"

Example2: Calculate the time difference between two dates

const startDate = new Date('2021-01-01');
const endDate = new Date('2021-12-31');

const timeDiff = endDate - startDate;

// Calculate the number of days between two datesconst daysDiff = (timeDiff / (1000 * 60 * 60 * 24));

// Calculate the number of hours between two datesconst hoursDiff = (timeDiff / (1000 * 60 * 60));

// Calculate the number of minutes between two datesconst minutesDiff = (timeDiff / (1000 * 60));

// Calculate the number of seconds between two datesconst secondsDiff = (timeDiff / 1000);

、、With examples1Much the same、、、、

Example 3: Set a specific date and time:

const date = new Date();

// Set date to January 1, 2022(2022);
(0);
(1);

// Set the time to 0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:(0);
(0);
(0);

// Get the set date and timeconst formattedDate1 = ();
const formattedTime2 = ();

Example 4: Get the date element

In many scenarios,We need to obtain the year of the date separately、moon、Elements such as day。
We can usegetFullYear()、getMonth()、getDate()Wait for this。

let now = new Date();
let year = (); // Get four-digit yearslet month = (); // Note that the months are counted from 0, so you need to add 1let day = ();

(`${year}/${month + 1}/${day}`); // The output is similar "2022/6/20"

Example 5: Format date

To be beautiful or adapt to user preferences,We usually need to format the date into a specific string。
Here we use template literals andpadStart()Method to implement:

function formatDate(date) {
  let year = ();
  let month = `0${() + 1}`.slice(-2);
  let day = `0${()}`.slice(-2);

  return `${year}-${month}-${day}`;
}

let today = new Date();
(formatDate(today)); // The output is similar "2022-06-20"

Attachment: Daily methods

The date of entry Timestamp
new Date("2022-08-21 11:12:13").getTime() 		// 1661051533000

The date of entry Week(Note:day:0 ,one:1,two:2,three:3,Four:4,five:5,six:6)
new Date("2022-08-21 11:12:13").getDay()        // 0

The date of entry Year
new Date("2022-08-21 11:12:13").getFullYear()  	// 2022

The date of entry moon -1 
new Date("2022-08-21 11:12:13").getMonth()  	// 7

The date of entry day
new Date("2022-08-21 11:12:13").getDate() 		// 21

The date of entry hour
new Date("2022-08-21 11:12:13").getHours() 		// 11

The date of entry point
new Date("2022-08-21 11:12:13").getMinutes()  	// 12

The date of entry Second
new Date("2022-08-21 11:12:13").getSeconds() 	// 13

The date of entry 毫Second (Note:The largest999)
new Date("2022-08-21 11:12:13:999").getMilliseconds()  //999

Summarize

This is the end of this article about the time and date function new Date() in JavaScript. For more related contents of JS time and date function new Date(), please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!