Solve the problem of MongoDB storage time difference

Source: Internet
Author: User
Tags local time mongodb

When MongoDB stores the time type data, it is converted to UTC time, then stored in the database, and when we take out the stored time, there is the problem of jet lag. For example, we use the Beijing time, read the value will see the current time is less than 8 hours, it is said that each time we read a separate processing time, which is more troublesome. In fact, we can do the appropriate processing when storing, just use the getTimezoneOffset () and the toisostring () function.

getTimezoneOffset function: Returns the difference in this area (local time versus GMT Greenwich Mean Time) in minutes.
<script>  // 我们是东八区  var d = new Date();  var tz = d.getTimezoneOffset();  console.log(tz);  // -480</script>
Toisostring () function: Converts a Date object to a string using the ISO standard.

The standard is called ISO-8601, in the form of: Yyyy-mm-ddthh:mm:ss.sssz.

Package Time conversion function
localDate(v) {    const d = new Date(v || Date.now());    d.setMinutes(d.getMinutes() - d.getTimezoneOffset());    return d.toISOString();},

When we store time, we call Localdate (), which is the same, no matter what time zone you are in, the results show the same as local time.

Solve the problem of MongoDB storage time difference

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.