JavaScript time function and formatted timestamp practice

Table of contents

1. Get the current time

2. Get a specific time

3. Get timestamp

4. Format timestamp as string

5. Calculate time difference

6. Convert time string into timestamp

Summarize

Node.js advanced use of superagent and cheerio modules is explained in detail and implements a simple crawler case

Node.js development advanced JavaScript function naming method and detailed explanation of self-executing anonymous functions


picture

There are many built-in functions and methods in JavaScript for working with time and date. These functions and methods can help us get the current time, format timestamps, calculate time differences, etc. This article will introduce in detail the commonly used time functions in JavaScript and how to format timestamps.

Original text of this article: JavaScript time function and formatted timestamp practice

For more technical points related to JavaScript, please pay attention to the public account CTO Plus below

picture

1. Get the current time

JavaScript provides a `Date` object to represent time and date. You can use `new Date()` to create a `Date` object representing the current time.

let now = new Date(); //Create object and return current timestamp

// Output the date and time of the current time

console.log(now, typeof now); // 2023-06-23T14:26:35.445Z object

2. Get a specific time

In addition to getting the current time, we can also get a specific time by passing parameters to the `Date` object.

let specificTime = new Date(2023, 6, 23, 12, 30, 0);

console.log(specificTime, typeof specificTime);//2023-07-23T04:30:00.000Z object

In the above example, we passed the year, month, day, hour, minutes and seconds as parameters to get a specific time.

3. Get timestamp

The timestamp is the number of milliseconds that have elapsed since midnight (Greenwich Mean Time) on January 1, 1970. You can use the `getTime()` method of the `Date` object to get the timestamp of the current time. You can use the Date.now() and date.getTime() methods to obtain a timestamp.

Use Date.now() to obtain the current timestamp. It is a static method and does not require creating an object.

console.log(Date.now()); // 1687530990595

let timestamp = new Date().getTime();

// Output the timestamp of the current time

console.log(timestamp, now.getTime(), typeof timestamp); // 1687530604090 1687530604072 number

4. Format timestamp as string

Formatting a timestamp is to convert the timestamp into a specific time format. There is no built-in function in JavaScript for formatting timestamps, but there are methods you can use to do so.

function formatTimestamp(timestamp) {
   
     let date = new Date(timestamp);  let year = date.getFullYear();  let month = date.getMonth() + 1;  let day = date.getDate();  let hours = date.getHours();  let minutes = date.getMinutes();  let seconds = date.getSeconds();    return `${year}-${addZero(month)}-${addZero(day)} ${addZero(hours)}:${addZero(minutes)}:${addZero(seconds)}`;}
function addZero(num) {
   
     return num < 10 ? `0${num}` : num;}
let formattedTime = formatTimestamp(timestamp);// 输出格式化后的时间字符串console.log(formattedTime); // //2023-06-23 22:31:51 string 

In the above example, we defined a `formatTimestamp()` function that accepts a timestamp as a parameter and returns a formatted time string. We use the methods of the `Date` object to get the year, month, day, hour, minutes and seconds and use the `addZero()` function to add leading zeros when the number is less than 10.

5. Calculate time difference

You can use the method of `Date` object to calculate the time difference in JavaScript. For example, you can use the `getTime()` method to get the timestamps of two times and then calculate the difference between them.

let startTime = new Date(2023, 6, 23, 12, 0, 0);

let endTime = new Date(2023, 6, 23, 13, 30, 0);

let diff = endTime.getTime() - startTime.getTime();

//Output the time difference in milliseconds

console.log(diff, typeof diff); //5400000 number

In the above example, we create two `Date` objects to represent the start time and end time, then use the `getTime()` method to get their timestamps and calculate the difference between them.

6. Convert time string into timestamp

Date.parse() converts a time string into a timestamp

console.log(Date.parse("2023-06-23 22:31:51")); // 1687530711000, static method

Summarize

JavaScript provides many built-in functions and methods for working with time and date. Through the `Date` object, we can get the current time, specific time, timestamp, and calculate the time difference. For formatting timestamps, although JavaScript does not have a built-in function, you can use a custom method to achieve it. In actual development, choose appropriate time functions and methods to process time and date according to specific needs.

Big front-end column
https://blog.csdn.net/zhouruifu2015/category_5734911

For more exciting news, follow my official account and learn and grow together.

Recommended reading in the Node.js series of articles:

  • Open source projects | Summary of the 25 most popular front-end development plug-ins (libraries) for JavaScript

  • Detailed explanation of several very useful global objects, global variables and global functions in Node.js

  • Detailed introduction and use cases of Node.js’ heroku tool to simplify application deployment and management

  • Node.js advanced use of superagent and cheerio modules is explained in detail and implements a simple crawler case

  • Node.js development advanced JavaScript function naming method and detailed explanation of self-executing anonymous functions

Big front-end column
https://blog.csdn.net/zhouruifu2015/category_5734911 https://blog.csdn.net/zhouruifu2015/category_5734911 Node.js column

https://blog.csdn.net/zhouruifu2015/category_5728369.htmlhttps://blog.csdn.net/zhouruifu2015/category_5728369.html


More information· Search [CTO Plus] on the WeChat public account and follow it to get more information. Let’s learn and communicate together.

For a description of the public account, visit the following link


About Articulate "Be a porter of knowledge and technology. Be a lifelong learning enthusiast. Be a technical circle with depth and breadth." I have always wanted to develop skills in the professional field https://mp.weixin.qq. com/s/0yqGBPbOI6QxHqK17WxU8Q

Recommended reading:

Guess you like

Origin blog.csdn.net/zhouruifu2015/article/details/132304296