Home Backend Development PHP Tutorial php gets time (system time and network time)

php gets time (system time and network time)

Jul 29, 2016 am 09:15 AM
date explode fsockopen time

When using php, you may often use standard time. There are two methods.

The first method:

Get the server time

First configure date.timezone = PRC in php.inior add date_default_timezone_set("PRC"); directly on the program page. Then you can use time ()ordate(''Y-m-d H:i:s)

The second method: get the network time (here is borrowed from the Internet, original address: http://justcoding.iteye.com/blog/843645 )

There is a situation like this, such as the booking process in the air ticket business. We need a very reliable current time to support it. Although the time of most servers is very accurate, we use time() to obtain it. The time is reliable, but there may be inaccuracies. Some servers do not enable ntp (Network Time Protocol) for time synchronization, and due to factors such as the hardware environment, the time may vary. In general, there is only one difference. A few minutes or at most a few hours is understandable because the same time is used on the same website, but sometimes this is bad. On the Internet, there are free timing servers that specifically provide UTC time correction, using the NTP protocol. You can refer to the previous link for more knowledge. The time error he provides is about 20ms (not to mention the time that will be consumed during the data transmission process, NTP has long considered this), so through this timing server, we can get a very reliable current time.

Let’s now take a look at how to get a very accurate UTC time using PHP. Since the NTP protocol is a little bit difficult to use, we have a better protocol to use, which is the Daytime Protocol. Through this protocol We can get the text data directly, which will be more convenient to process. We use the time service of time.nist.gov. The code is very simple. Just use TCP to connect to its port 13.

<code><span>$fp</span>=fsockopen(<span>'time.nist.gov'</span>,<span>13</span>,<span>$errno</span>,<span>$errstr</span>,<span>90</span>);  
<span>echo</span> fread(<span>$fp</span>,<span>2010</span>);  </code>
Copy after login

The data obtained is similar to this:

<code>55545 10<span>-12-15</span> 21<span>:40</span><span>:47</span> 00 0 0 113<span>.1</span><span>UTC</span>(<span>NIST</span>) *  </code>
Copy after login

Every part of this string is meaningful. For details, please see: http://www.nist.gov/pml/div688/grp40/its.cfm, Now we only care about the middle part and the 0 in front of 206.9, which represents the health status of the server and also reflects whether the current time is trustworthy.

OK, use PHP to obtain accurate UTC time. This application is still very valuable in situations where time requirements are very strict. At this point, my problem is solved.

Now that we know the UTC standard time, the only thing left is to convert it into world time. See php to get the local time time zone

<code><span>$fp</span>=fsockopen(<span>'time.nist.gov'</span>,<span>13</span>,<span>$errno</span>,<span>$errstr</span>,<span>90</span>);  
<span>$ufc</span> = explode(<span>' '</span>,fread(<span>$fp</span>,date(<span>'Y'</span>)));  
<span>$date</span> = explode(<span>'-'</span>,<span>$ufc</span>[<span>1</span>]);  
<span>$processdate</span> = <span>$date</span>[<span>1</span>].<span>'-'</span>.<span>$date</span>[<span>2</span>].<span>'-'</span>. date(<span>'Y'</span>).<span>' '</span>.<span>$ufc</span>[<span>2</span>];  

<span>switch</span>(<span>$ufc</span>[<span>5</span>])  
{  
    <span>case</span><span>0</span>: <span>echo</span><span>'精确'</span>; <span>break</span>;  

    <span>case</span><span>1</span>: <span>echo</span><span>'误差:0-5s'</span>; <span>break</span>;    

    <span>case</span><span>2</span>: <span>echo</span><span>'误差: > 5s'</span>; <span>break</span>;  

    <span>default</span>: <span>echo</span><span>'硬件出错!'</span>; <span>break</span>;  
}  

<span>echo</span> gmttolocal(<span>$processdate</span>,<span>8</span>); <span>// 中国  </span><span><span>function</span><span>gmttolocal</span><span>(<span>$mydate</span>,<span>$mydifference</span>)</span>{</span><span>$datetime</span> = explode(<span>" "</span>,<span>$mydate</span>);  
    <span>$dateexplode</span> = explode(<span>"-"</span>,<span>$datetime</span>[<span>0</span>]);  
    <span>$timeexplode</span> = explode(<span>":"</span>,<span>$datetime</span>[<span>1</span>]);  
    <span>$unixdatetime</span> = mktime(<span>$timeexplode</span>[<span>0</span>]+<span>$mydifference</span>,<span>$timeexplode</span>[<span>1</span>],<span>0</span>,<span>$dateexplode</span>[<span>0</span>],<span>$dateexplode</span>[<span>1</span>],<span>$dateexplode</span>[<span>2</span>]);  
    <span>return</span> date(<span>"m/d/Y H:i:s"</span>,<span>$unixdatetime</span>);  
}  </code>
Copy after login

fsockopen explanation:

Open the Socket link of the network.
Syntax: int fsockopen(string hostname, int port, int [errno], string [errstr], int [timeout]);
Return value: integer
Function type: Network system

Content Description Currently, this function provides two Socket data flow interfaces, namely AF_INET for Internet and AF_UNIX for Unix. When used in the context of the Internet, the parameters hostname and port represent the URL and port number respectively. In the case of UNIX, you can do IPC, the hostname parameter indicates the path to the socket, and the port is configured as 0. The omitted timeout option indicates how long it will take before the connection is interrupted. After using this function, the file pointer will be returned for use by file functions, including fgets(), fgetss(), fputs(), fclose() and feof(). The parameters errno and errstr are also omitted and are mainly used for error handling. Using this function will use blocking mode processing, which can be converted to non-blocking mode with set_socket_blocking().

Author:leedaning
URL of this article: http://blog.csdn.net/leedaning/article/details/48547123

The above introduces the PHP acquisition time (system time and network time), including the relevant content. I hope it will be helpful to friends who are interested in PHP tutorials.

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

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

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)

Hot Topics

Java Tutorial
1664
14
PHP Tutorial
1268
29
C# Tutorial
1246
24
PHP Warning: date() expects parameter 2 to be long, string given solution PHP Warning: date() expects parameter 2 to be long, string given solution Jun 22, 2023 pm 08:03 PM

When developing using PHP programs, you often encounter some warning or error messages. Among them, one error message that may appear is: PHPWarning:date()expectsparameter2tobelong,stringgiven. The error message means: the second parameter of the function date() is expected to be a long integer (long), but what is actually passed to it is a string (string). So, we

How to create and name a file/folder based on current timestamp How to create and name a file/folder based on current timestamp Apr 27, 2023 pm 11:07 PM

If you're looking for a way to automatically create and name files and folders based on system timestamps, you've come to the right place. There is a super simple way to accomplish this task. The created folders or files can then be used for various purposes such as storing file backups, sorting files based on date, etc. In this article, we will explain in some very simple steps how to automatically create files and folders in Windows 11/10 and name them according to the system’s timestamp. The method used is a batch script, which is very simple. Hope you enjoyed reading this article. Section 1: How to automatically create and name a folder based on the current timestamp of the system Step 1: First, navigate to the parent folder where you want to create the folder,

How to get the millisecond representation of a date using the getTime() method of the Date class How to get the millisecond representation of a date using the getTime() method of the Date class Jul 24, 2023 am 11:42 AM

How to get millisecond representation of date using getTime() method of Date class In Java, Date class is a class used to represent date and time. It provides many useful methods to manipulate and obtain information about date objects. Among them, the getTime() method is an important method in the Date class, which can return the millisecond representation of the date object. Next, we will detail how to use this method to obtain the millisecond representation of a date, and provide corresponding code examples. Using the Date class

Monotonic clock processing of time package Monotonic clock processing of time package Aug 04, 2023 pm 05:45 PM

Today we are mainly going to take a look at the time application method of golang time package. The general rule between the two is that "wall time" is used to tell time, and "monotonic clock" is used to measure time; there are other clock processing methods.

Introduction to methods and usage of using Date and SimpleDateFormat classes to process time in Java Introduction to methods and usage of using Date and SimpleDateFormat classes to process time in Java Apr 21, 2023 pm 03:01 PM

1. Introduction The Date class in the java.util package represents a specific time, accurate to milliseconds. If we want to use our Date class, then we must introduce our Date class. Writing the year directly into the Date class will not produce the correct result. Because Date in Java is calculated from 1900, so as long as you fill in the first parameter with the number of years since 1900, you will get the year you want. The month needs to be subtracted by 1, and the day can be inserted directly. This method is rarely used, and the second method is commonly used. This method is to convert a string that conforms to a specific format, such as yyyy-MM-dd, into Date type data. First, define an object of Date type Date

How to use PHP explode function and solve errors How to use PHP explode function and solve errors Mar 10, 2024 am 09:18 AM

The explode function in PHP is a function used to split a string into an array. It is very common and flexible. In the process of using the explode function, we often encounter some errors and problems. This article will introduce the basic usage of the explode function and provide some methods to solve the error reports. 1. Basic usage of the explode function In PHP, the basic syntax of the explode function is as follows: explode(string$separator,string$stri

What are the options for calendar and date libraries in Python? What are the options for calendar and date libraries in Python? Oct 21, 2023 am 09:22 AM

There are many excellent calendar libraries and date libraries in Python for us to use. These libraries can help us handle date and calendar related operations. Next, I will introduce you to several common choices and provide corresponding code examples. Datetime library: Datetime is Python's built-in date and time processing module. It provides many date and time related classes and methods, which can be used to process dates, times, time differences and other operations. Sample code: importdatetime#Get the current date

Common errors and solutions when using the explode function in PHP Common errors and solutions when using the explode function in PHP Mar 11, 2024 am 08:33 AM

Title: Common errors and solutions when using the explode function in PHP In PHP, the explode function is a common function used to split a string into an array. However, some common errors can occur due to improper use or incorrect data format. This article will analyze the problems you may encounter when using the explode function, and provide solutions and specific code examples. Mistake 1: The delimiter parameter is not passed in. When using the explode function, one of the most common mistakes is that the delimiter parameter is not passed in.

See all articles