Conversion between Timestamp and date in node. js

Source: Internet
Author: User

Conversion between Timestamp and date in node. js

Today, when I was working on a project, I encountered the problem that the time stamp and date must be converted. I have been busy for a long time. Here I will summarize and record it.

First, let's take a look at the Date object in js. The Date object is the Date and time operation interface provided by JavaScript. It has multiple usage methods.

1. new Date (milliseconds): The Date object takes the number of milliseconds calculated from 00:00:00 UTC on January 1, January 1, 1970 as the parameter. This means that if the Unix timestamp is used as a parameter, the Unix timestamp must be multiplied by 1000.

UNIX timestamp: the number of seconds since January 1, January 1, 1970 (midnight in UTC/GMT). Note that it is a second, and the date object receives a millisecond.

2. new Date ("21:00:00 ");

The object receives a standard Date Format String and converts it to the corresponding time:


3. date. getTime ();

Returns the number of seconds that have elapsed since January 1, January 1, 1970 (midnight UTC/GMT;


Therefore, we obtain the timestamp of the date given in string form as follows: <喎?http: www.bkjia.com kf ware vc " target="_blank" class="keylink"> VcD4KPHA + PHByZSBjbGFzcz0 = "brush: java;"> var date = new Date ("21:00:00"); var time = date. getTime ()/1000; // convert to seconds;We then convert it to the date format:

Var date = new Date (time * 1000); //. Convert to millisecond var time = date. getFullYear () + "-" + (date. getMonth () <10? '0' + (date. getMonth () + 1): (date. getMonth () + 1) + "-" + (date. getDate () <10? '0' + date. getDate (): date. getDate ());
Output:


As you can see, the last line outputs the date and time!

So how can we obtain the timestamp of the current time? It's actually quite easy!

Date. now () gets the timestamp of the current time, and the output is millisecond.


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.