Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get date and time from server

Tags:

php

datetime

I want to retrieve date and time from server and according to it do some thing. For this I used following code:

$info = getdate(); $date = $info['mday']; $month = $info['mon']; $year = $info['year']; $hour = $info['hours']; $min = $info['minutes']; $sec = $info['seconds'];  $current_date = "$date/$month/$year == $hour:$min:$sec"; 

This code returns proper date but problem is that what I see in my cpanel(server time) is diff. than what I get from code. In cpanel time is CDT while from code it is showing UTC which I reconfirm using following code

<?php echo date("r == e"); ?> 

Why this is happening and what changes I have to do in my code so that I can get proper server time.

like image 796
user392406 Avatar asked Jul 08 '11 07:07

user392406


People also ask

How do I find the server time and date?

To display current date and time under Linux operating system using command prompt use the date command or timedatectl command. These commands can also display the current time / date in the given FORMAT. We can set the system date and time as root user too.

How do I get the current date on a server?

Usage Options. SQL Server provides several different functions that return the current date time including: GETDATE(), SYSDATETIME(), and CURRENT_TIMESTAMP. The GETDATE() and CURRENT_TIMESTAMP functions are interchangeable and return a datetime data type. The SYSDATETIME() function returns a datetime2 data type.

How to get time from server in PHP?

Answer: Use the PHP date() Function You can simply use the PHP date() function to get the current data and time in various format, for example, date('d-m-y h:i:s') , date('d/m/y H:i:s') , and so on.


2 Answers

You should set the timezone to the one of the timezones you want.

// set default timezone date_default_timezone_set('America/Chicago'); // CDT  $info = getdate(); $date = $info['mday']; $month = $info['mon']; $year = $info['year']; $hour = $info['hours']; $min = $info['minutes']; $sec = $info['seconds'];  $current_date = "$date/$month/$year == $hour:$min:$sec"; 

Or a much shorter version:

// set default timezone date_default_timezone_set('America/Chicago'); // CDT  $current_date = date('d/m/Y == H:i:s'); 
like image 113
Shef Avatar answered Oct 05 '22 17:10

Shef


Try this -

<?php date_default_timezone_set('Asia/Kolkata');  $timestamp = time(); $date_time = date("d-m-Y (D) H:i:s", $timestamp); echo "Current date and local time on this server is $date_time"; ?> 
like image 45
Rohit Suthar Avatar answered Oct 05 '22 19:10

Rohit Suthar