Home Web Front-end Front-end Q&A javascript timestamp conversion cycle

javascript timestamp conversion cycle

May 09, 2023 am 10:25 AM

With the continuous development of the Internet and the popularity of applications, timestamps, as a commonly used time representation method, are widely used in various data interaction scenarios. For front-end developers, it is often necessary to convert timestamps so that they can be presented to users more intuitively, while also facilitating back-end data interaction.

In JavaScript, timestamp is a unit of time expressed in milliseconds, but in actual use we are more accustomed to expressing time in units of cycles, such as year, month, day, hour, minute, and second. wait. Therefore, this article will describe how to use JavaScript to convert a timestamp into a representation of time in various periodic units.

  1. Convert timestamp to time string

In JavaScript, we can use the toLocaleString() method of the Date object to convert the timestamp into a local time string. This method returns a string. The format of the string varies according to different locales, such as "2022/01/01 1:00:00 PM".

Code example:

const timestamp = 1641010800000; // 时间戳,单位为毫秒
const date = new Date(timestamp);
const localTimeString = date.toLocaleString(); // 本地时间字符串
console.log(localTimeString);
Copy after login
  1. Convert timestamp to date string

In addition to converting timestamp to local time string, you can also It is converted into a string in calendar date format, that is, only the year, month, and day parts are retained. This can be achieved by using the toLocaleDateString() method of the Date object.

Code example:

const timestamp = 1641010800000; // 时间戳,单位为毫秒
const date = new Date(timestamp);
const dateString = date.toLocaleDateString(); // 日期字符串
console.log(dateString);
Copy after login
  1. Convert timestamp to time string (excluding date)

If we only need to keep the part of the time, we can Use the Date object's toLocaleTimeString() method.

Code example:

const timestamp = 1641010800000; // 时间戳,单位为毫秒
const date = new Date(timestamp);
const timeString = date.toLocaleTimeString(); // 时间字符串(不包含日期)
console.log(timeString);
Copy after login
  1. Convert timestamp to time object

The Date object in JavaScript can not only convert timestamp to string format, It can also be converted into a time object, containing information such as year, month, day, hour, minute, second, etc.

Code example:

const timestamp = 1641010800000; // 时间戳,单位为毫秒
const date = new Date(timestamp);
const year = date.getFullYear(); // 年
const month = date.getMonth() + 1; // 月(注意要加上1)
const day = date.getDate(); // 日
const hour = date.getHours(); // 时
const minute = date.getMinutes(); // 分
const second = date.getSeconds(); // 秒
console.log(year, month, day, hour, minute, second);
Copy after login
  1. Convert timestamp to hour, minute and second representation

Sometimes we only need to get the hour, minute and second part of the time, which can be calculated The difference between the timestamp and the zero time timestamp of the day, and perform unit conversion to obtain the representation of hours, minutes and seconds.

Code sample:

const timestamp = 1641010800000; // 时间戳,单位为毫秒
const date = new Date(timestamp);
const zeroTimestamp = new Date(date.getFullYear(), date.getMonth(), date.getDate()).getTime(); // 当天零点的时间戳
const diff = (timestamp - zeroTimestamp) / 1000; // 时间戳与当天零点时间戳之间的差值,单位为秒
const hour = Math.floor(diff / 3600); // 小时
const minute = Math.floor((diff % 3600) / 60); // 分钟
const second = Math.floor(diff % 60); // 秒
console.log(hour, minute, second);
Copy after login

Summary:

In JavaScript, converting timestamps into time representations in various period units can be achieved by using various methods of the Date object , including toLocaleString(), toLocaleDateString(), toLocaleTimeString(), getFullYear(), etc. At the same time, the time difference can also be calculated to obtain expressions such as hours, minutes, and seconds. The above method can meet most of the time conversion needs, while also giving developers enough freedom to carry out customized development as needed to improve user experience.

The above is the detailed content of javascript timestamp conversion cycle. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
1 months ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
1 months ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
1 months ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Chat Commands and How to Use Them
1 months ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

What is useEffect? How do you use it to perform side effects? What is useEffect? How do you use it to perform side effects? Mar 19, 2025 pm 03:58 PM

The article discusses useEffect in React, a hook for managing side effects like data fetching and DOM manipulation in functional components. It explains usage, common side effects, and cleanup to prevent issues like memory leaks.

How does the React reconciliation algorithm work? How does the React reconciliation algorithm work? Mar 18, 2025 pm 01:58 PM

The article explains React's reconciliation algorithm, which efficiently updates the DOM by comparing Virtual DOM trees. It discusses performance benefits, optimization techniques, and impacts on user experience.Character count: 159

What are higher-order functions in JavaScript, and how can they be used to write more concise and reusable code? What are higher-order functions in JavaScript, and how can they be used to write more concise and reusable code? Mar 18, 2025 pm 01:44 PM

Higher-order functions in JavaScript enhance code conciseness, reusability, modularity, and performance through abstraction, common patterns, and optimization techniques.

How does currying work in JavaScript, and what are its benefits? How does currying work in JavaScript, and what are its benefits? Mar 18, 2025 pm 01:45 PM

The article discusses currying in JavaScript, a technique transforming multi-argument functions into single-argument function sequences. It explores currying's implementation, benefits like partial application, and practical uses, enhancing code read

How do you connect React components to the Redux store using connect()? How do you connect React components to the Redux store using connect()? Mar 21, 2025 pm 06:23 PM

Article discusses connecting React components to Redux store using connect(), explaining mapStateToProps, mapDispatchToProps, and performance impacts.

What is useContext? How do you use it to share state between components? What is useContext? How do you use it to share state between components? Mar 19, 2025 pm 03:59 PM

The article explains useContext in React, which simplifies state management by avoiding prop drilling. It discusses benefits like centralized state and performance improvements through reduced re-renders.

How do you prevent default behavior in event handlers? How do you prevent default behavior in event handlers? Mar 19, 2025 pm 04:10 PM

Article discusses preventing default behavior in event handlers using preventDefault() method, its benefits like enhanced user experience, and potential issues like accessibility concerns.

What are the advantages and disadvantages of controlled and uncontrolled components? What are the advantages and disadvantages of controlled and uncontrolled components? Mar 19, 2025 pm 04:16 PM

The article discusses the advantages and disadvantages of controlled and uncontrolled components in React, focusing on aspects like predictability, performance, and use cases. It advises on factors to consider when choosing between them.

See all articles