search
HomeWeb Front-endJS TutorialDetailed explanation of JavaScript UTC time conversion method_javascript skills

1. Foreword
1. UTC: Universal Time Coordinated, coordinated universal time.
2. Greenwich Mean Time (GMT)
Greenwich Mean Time (GMT) refers to the standard time at the Royal Greenwich Observatory in the suburbs of London, because the prime meridian is defined as the longitude passing there. Theoretically, noon in Greenwich Mean Time is when the sun crosses the Greenwich meridian. Due to the uneven motion of the Earth in its elliptical orbit, this time may differ from actual solar time by 16 minutes. The Earth's daily rotation is somewhat irregular and is slowly slowing down. Therefore, GMT is no longer used as standard time. Today's standard time - Coordinated Universal Time (UTC) - is provided by atomic clocks. Since February 5, 1924, the Greenwich Observatory has sent time adjustment information to the world every hour. UTC is based on the accurate time provided by the standard GMT.
GMT (Greenwich Mean Time) - Greenwich Mean Time. Greenwich Mean Time was the reference time of the British Empire in the mid-19th century and was also the de facto world reference time. At that time it was mainly used to serve the railway system after 1840. It uses the longitude of the Greenwich Observatory as the 0-degree longitude and divides the world into 24 time zones. Except for being affected by xenophobia, nationalism and some anti-British sentiments at certain times, its status has never been shaken.

The difference between GMT and UTC
A GMT watch is a watch that can display the time in two or more time zones. No matter what method is used, the most direct way to display multiple time zones is to install multiple movements in one watch case. However, the most economical and common method is to attach a rotating bezel with a 12-hour or 24-hour time scale. The method of using the rotating bezel is very simple. Just align the number on the bezel corresponding to the second time zone time with the hour hand of the dial. If the dial time is London time, then turn the bezel clockwise for one hour to indicate continental European time. , turn counterclockwise eight hours, which is the West Coast Time of the United States.
​Whether the dial time is set to home time or destination time depends on the user's preference, but since the 12-hour watch cannot distinguish between day and night, it is usually more reasonable to set the local time. An event occurred that complicated the definition of GMT: on January 1, 1972, UTC (Coordinated Universal Time) became the new universal standard time.
For convenience, it is usually recorded as Universal Time Coordinated. Also for convenience, GMT and UTC are often treated as equivalent when precision to the second is not required. Although UTC is more scientific and accurate, GMT is still more popular among watch players and collectors. Many people believe that UTC is a means for Paris to seek status as the world's timing center. In fact, it is a time measurement system based on atomic time and as close to universal time as possible. Its emergence is the need for precise timing in modern society.
Atomic time is different from previous timing systems. It is very accurate and is not based on the mean solar time of a certain place. However, when the earth's rotation speed is uneven, the time difference between atomic time and universal time accumulates over time. Therefore, UTC will be in Positive or negative leap seconds are added after a period of time to compensate. Therefore there will be a number of whole seconds difference between Coordinated Universal Time and International Atomic Time (TAI). The International Central Bureau for Earth Rotation Affairs (IERS) in Paris is responsible for deciding when to include leap seconds.

Beijing time is 8 time zones different from Greenwich Time or UTC time. Beijing, Shanghai, and Chongqing are located in the 8th East Zone, so Beijing time 2013-1-1 0:00:00, converted to UTC time is: Tue Jan 1 00 :00:00 UTC+0800 2013, 8 hours later.
2. Conversion from local time to UTC time
Conversion from local time to UTC time, the steps are as follows:

1. Convert string date to date data type
If it is already a date type, you can omit this step.

Can be converted using the function in the example below.
2. Get UTC date data
Including year, month, day, hour, minute and second, use getUTC***() method to obtain.

Get the year: var y = date.getUTCFulYear();
Get the month: var m = date.getUTCMonth();
Get the date: var d = date.getUTCDate();
Get the hour: var h= date.getUTCHours();
Get minutes: var M = date.getUTCMinutes();
Get seconds: var s = date.getUTCSeconds();

The date here is date type data.

Note: There is a problem with using methods without UTC here (for example: date.getFullYear, date.getMonth). When performing the next conversion, a result error will occur.

3. Use the Date.UTC() function to convert
Convert the date data obtained in step 2 to UTC time (actually milliseconds since 1700)

var utc = Date.UTC(y,m,d,h,M,s);

这里,y、m、d、h、M、s分别代表步骤2中获取的年、月、日、时、分、秒数值。

三、UTC日期到本地日期的转换
UTC日期到本地日期转换则要简单得多,先将UTC时间转换为日期格式,然后再转换为本地日期格式,例如:

var date2 = new Date(utc);

var localeString = date2.toLocaleString();

或只要日期

var localeDateString = date2.toLocaleDateString();

或只要时间

var localeTimeString = date2.toLocaleTimeString();

实例:

//日期加减计算 
function dateadd(sdate, delta, ymdh){ 
 if(!sdate ) return; 
  
 if(typeof sdate == 'object') sdate = sdate.toLocaleString(); 
 
 /(\d{4})[\D](\d{1,2})[\D](\d{1,2})[\D]?\s(\d{1,2}):(\d{1,2}):(\d{1,2})/.exec(sdate); 
 var a = [0,0,0,0]; 
  
 switch(ymdh){ 
  case 'y': 
   a = [delta, -1, 0, 0]; 
   break; 
  case 'm': 
   a=[0, delta-1, 0, 0]; 
   break; 
  case 'H': 
   a=[0, -1, 0, delta]; 
   break;  
  default: 
   a = [0, -1, delta, 0]; 
   break;   
 } 
  
 println('date:' + (parseInt(RegExp.$1)+ a[0]) + '-'+ (parseInt(RegExp.$2)+a[1]) +'-' + (parseInt(RegExp.$3)+a[2]) 
  + ' ' + (parseInt(RegExp.$4)+a[3]) +':' + RegExp.$5 + ':' +RegExp.$6); 
  
 return new Date(parseInt(RegExp.$1)+ a[0], parseInt(RegExp.$2)+a[1], parseInt(RegExp.$3)+a[2], parseInt(RegExp.$4)+a[3], RegExp.$5,RegExp.$6); 
} 
 
 //UTC转换 
 println('---------------------------------------------'); 
 var sdate='2013-01-01 00:00:00.0'; 
 var d = dateadd(sdate,0); 
 var d2 = Date.UTC(d.getUTCFullYear(),d.getUTCMonth() ,d.getUTCDate(),d.getUTCHours(),d.getUTCMinutes(),d.getUTCSeconds()); 
 println('原日期:' + sdate); 
 println('d2:' + d2); 
 println('d3:' + new Date(d2)); 
 println('d4:' + new Date(d2).toLocaleString()); 
 println('d5:' + d2.toLocaleString()); 

测试结果:

---------------------------------------------
date:2013-0-1 0:00:00
原日期:2013-01-01 00:00:00.0
d2:1356969600000
d3:Tue Jan 1 00:00:00 UTC+0800 2013
d4:2013年1月1日 0:00:00
d5:1,356,969,600,000.00

可以看到UTC时间实际上是一串以自1970年以来的毫秒数表示的长数字。

以上就是本文的全部内容,希望对大家的学习有所帮助。

Statement
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
Beyond the Browser: JavaScript in the Real WorldBeyond the Browser: JavaScript in the Real WorldApr 12, 2025 am 12:06 AM

JavaScript's applications in the real world include server-side programming, mobile application development and Internet of Things control: 1. Server-side programming is realized through Node.js, suitable for high concurrent request processing. 2. Mobile application development is carried out through ReactNative and supports cross-platform deployment. 3. Used for IoT device control through Johnny-Five library, suitable for hardware interaction.

Building a Multi-Tenant SaaS Application with Next.js (Backend Integration)Building a Multi-Tenant SaaS Application with Next.js (Backend Integration)Apr 11, 2025 am 08:23 AM

I built a functional multi-tenant SaaS application (an EdTech app) with your everyday tech tool and you can do the same. First, what’s a multi-tenant SaaS application? Multi-tenant SaaS applications let you serve multiple customers from a sing

How to Build a Multi-Tenant SaaS Application with Next.js (Frontend Integration)How to Build a Multi-Tenant SaaS Application with Next.js (Frontend Integration)Apr 11, 2025 am 08:22 AM

This article demonstrates frontend integration with a backend secured by Permit, building a functional EdTech SaaS application using Next.js. The frontend fetches user permissions to control UI visibility and ensures API requests adhere to role-base

JavaScript: Exploring the Versatility of a Web LanguageJavaScript: Exploring the Versatility of a Web LanguageApr 11, 2025 am 12:01 AM

JavaScript is the core language of modern web development and is widely used for its diversity and flexibility. 1) Front-end development: build dynamic web pages and single-page applications through DOM operations and modern frameworks (such as React, Vue.js, Angular). 2) Server-side development: Node.js uses a non-blocking I/O model to handle high concurrency and real-time applications. 3) Mobile and desktop application development: cross-platform development is realized through ReactNative and Electron to improve development efficiency.

The Evolution of JavaScript: Current Trends and Future ProspectsThe Evolution of JavaScript: Current Trends and Future ProspectsApr 10, 2025 am 09:33 AM

The latest trends in JavaScript include the rise of TypeScript, the popularity of modern frameworks and libraries, and the application of WebAssembly. Future prospects cover more powerful type systems, the development of server-side JavaScript, the expansion of artificial intelligence and machine learning, and the potential of IoT and edge computing.

Demystifying JavaScript: What It Does and Why It MattersDemystifying JavaScript: What It Does and Why It MattersApr 09, 2025 am 12:07 AM

JavaScript is the cornerstone of modern web development, and its main functions include event-driven programming, dynamic content generation and asynchronous programming. 1) Event-driven programming allows web pages to change dynamically according to user operations. 2) Dynamic content generation allows page content to be adjusted according to conditions. 3) Asynchronous programming ensures that the user interface is not blocked. JavaScript is widely used in web interaction, single-page application and server-side development, greatly improving the flexibility of user experience and cross-platform development.

Is Python or JavaScript better?Is Python or JavaScript better?Apr 06, 2025 am 12:14 AM

Python is more suitable for data science and machine learning, while JavaScript is more suitable for front-end and full-stack development. 1. Python is known for its concise syntax and rich library ecosystem, and is suitable for data analysis and web development. 2. JavaScript is the core of front-end development. Node.js supports server-side programming and is suitable for full-stack development.

How do I install JavaScript?How do I install JavaScript?Apr 05, 2025 am 12:16 AM

JavaScript does not require installation because it is already built into modern browsers. You just need a text editor and a browser to get started. 1) In the browser environment, run it by embedding the HTML file through tags. 2) In the Node.js environment, after downloading and installing Node.js, run the JavaScript file through the command line.

See all articles

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)
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function