A Simple Method of two hours ago in JavaScript and UTC

Source: Internet
Author: User
Two hours ago

When you evaluate the time period control on the Interface today, you must obtain the current time and the time two hours before the current time. How can we implement it in JavaScript?

The new date () in javascript can get the current time.

The first thought was to use

VaR date = new date (). getdate ();

To obtain the number of hours of the current time, and then subtract two hours to calculate the desired result, but a lot of judgment is required. For example, after two hours, the threshold value of 0 is exceeded, yesterday, however, yesterday can be the last month, and the number of days in the last month must be recalculated. This is troublesome.

A good way is to skip these steps and check the following code:

VaR now = new date ();
VaR start = new date (0, 0, 0, 0, 0, 0, 0); // note that there are seven digits, and the last digit is millisecond.

// The difference between the current time and the minimum time, in milliseconds. The difference between the time before two hours and the minimum time is naturally 3600*1000*2 less than the current time.

VaR millis = now-start-3600*1000*2;

VaR twohoursago = new date (0, 0, 0, 0, 0, 0, millis );


UTC time of the current time

VaR time = new date ();
VaR utcsecond = time. gettimezoneoffset (); // you can find the difference between the current time and the current UTC time.
VaR interval = Time-new date (0, 0, 0, 0, 0, 0, 0) + utcsecond * 60000;
VaR utctime = new date (0, 0, 0, 0, 0, 0, interval );

 

 

 


 


 

 

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.