What is easiest way to display the current time in PST (West Coast) time using PHP?
Well, the easiest might be:
date_default_timezone_set('America/Los_Angeles');
echo date('Y-m-d');
Take a look at supported timezones to find one suitable for your needs.
Let's try a solution that uses PHP's modern date handling. This example requires PHP 5.2 or better.
// Right now it's about four minutes before 1 PM, PST.
$pst = new DateTimeZone('America/Los_Angeles');
$three_hours_ago = new DateTime('-3 hours', $pst); // first argument uses strtotime parsing
echo $three_hours_ago->format('Y-m-d H:i:s'); // "2010-06-15 09:56:36"
If you are using or have access to Carbon you could do this:
$timezone = 'America/Los_Angeles';
$now = Carbon::now()->tz($timezone)->toDateTimeString();
echo $now;
.
echo date('r');
putenv('TZ=PST');
echo date('r');
To convert a date/time between timezones:
include ("Date.php");
$d = new Date("2010-06-21 10:59:27"); // initialize object
$d->setTZByID("GMT"); // set local time zone
$d->convertTZByID("PST"); // convert to foreign time zone
echo $d->format("%A, %d %B %Y %T"); // retrieve converted date/time
Related
So I've checked the list of supported time zones in PHP and I was wondering how could I include them in the date() function?
Thanks!
I don't want a default timezone, each user has their timezone stored in the database, I take that timezone of the user and use it. How? I know how to take it from the database, not how to use it, though.
For such task, you should really be using PHP's DateTime class. Please ignore all of the answers advising you to use date() or date_set_time_zone, it's simply bad and outdated.
I'll use pseudocode to demonstrate, so try to adjust the code to suit your needs.
Assuming that variable $tz contains string name of a valid time zone and variable $timestamp contains the timestamp you wish to format according to time zone, the code would look like this:
$tz = 'Europe/London';
$timestamp = time();
$dt = new DateTime("now", new DateTimeZone($tz)); //first argument "must" be a string
$dt->setTimestamp($timestamp); //adjust the object to correct timestamp
echo $dt->format('d.m.Y, H:i:s');
DateTime class is powerful, and to grasp all of its capabilities - you should devote some of your time reading about it at php.net. To answer your question fully - yes, you can adjust the time zone parameter dynamically (on each iteration while reading from db, you can create a new DateTimeZone() object).
If I understood correct,You need to set time zone first like:
date_default_timezone_set('UTC');
And than you can use date function:
// Prints something like: Monday 8th of August 2005 03:12:46 PM
echo date('l jS \of F Y h:i:s A');
The answer above caused me to jump through some hoops/gotchas, so just posting the cleaner code that worked for me:
$dt = new DateTime();
$dt->setTimezone(new DateTimeZone('America/New_York'));
$dt->setTimestamp(123456789);
echo $dt->format('F j, Y # G:i');
Use the DateTime class instead, as it supports timezones. The DateTime equivalent of date() is DateTime::format.
An extremely helpful wrapper for DateTime is Carbon - definitely give it a look.
You'll want to store in the database as UTC and convert on the application level.
It should like this:
date_default_timezone_set('America/New_York');
U can just add, timezone difference to unix timestamp.
Example for Moscow (UTC+3)
echo date('d.m.Y H:i:s', time() + 3 * 60 * 60);
Try this. You can pass either unix timestamp, or datetime string
public static function convertToTimezone($timestamp, $fromTimezone, $toTimezone, $format='Y-m-d H:i:s')
{
$datetime = is_numeric($timestamp) ?
DateTime::createFromFormat ('U' , $timestamp, new DateTimeZone($fromTimezone)) :
new DateTime($timestamp, new DateTimeZone($fromTimezone));
$datetime->setTimezone(new DateTimeZone($toTimezone));
return $datetime->format($format);
}
this works perfectly in 2019:
date('Y-m-d H:i:s',strtotime($date. ' '.$timezone));
I have created this very straightforward function, and it works like a charm:
function ts2time($timestamp,$timezone){ /* input: 1518404518,America/Los_Angeles */
$date = new DateTime(date("d F Y H:i:s",$timestamp));
$date->setTimezone(new DateTimeZone($timezone));
$rt=$date->format('M d, Y h:i:s a'); /* output: Feb 11, 2018 7:01:58 pm */
return $rt;
}
I have tried the answers based on the DateTime class. While they are working, I found a much simpler solution that makes a DateTime object timezone aware at the time of creation.
$dt = new DateTime("now", new DateTimeZone('Asia/Jakarta'));
echo $dt->format("Y-m-d H:i:s");
This returns the current local time in Jakarta, Indonesia.
Not mentioned above. You could also crate a DateTime object by providing a timestamp as string in the constructor with a leading # sign.
$dt = new DateTime('#123456789');
$dt->setTimezone(new DateTimeZone('America/New_York'));
echo $dt->format('F j, Y - G:i');
See the documentation about compound formats:
https://www.php.net/manual/en/datetime.formats.compound.php
Based on other answers I built a one-liner, where I suppose you need current date time. It's easy to adjust if you need a different timestamp.
$dt = (new DateTime("now", new DateTimeZone('Europe/Rome')))->format('d-m-Y_His');
If you use Team EJ's answer, using T in the format string for DateTime will display a three-letter abbreviation, but you can get the long name of the timezone like this:
$date = new DateTime('2/3/2022 02:11:17');
$date->setTimezone(new DateTimeZone('America/Chicago'));
echo "\n" . $date->format('Y-m-d h:i:s T');
/* Displays 2022-02-03 02:11:17 CST "; */
$t = $date->getTimezone();
echo "\nTimezone: " . $t->getName();
/* Displays Timezone: America/Chicago */
$now = new DateTime();
$now->format('d-m-Y H:i:s T')
Will output:
29-12-2021 12:38:15 UTC
I had a weird problem on a hosting. The timezone was set correctly, when I checked it with the following code.
echo ini_get('date.timezone');
However, the time it returned was UTC.
The solution was using the following code since the timezone was set correctly in the PHP configuration.
date_default_timezone_set(ini_get('date.timezone'));
You can replace database value in date_default_timezone_set function,
date_default_timezone_set(SOME_PHP_VARIABLE);
but just needs to take care of exact values relevant to the timezones.
I have a UTC timestamp value 1615958170523 and I want to convert it into our local timezone.
I have tried this method:
The timestamp is in milliseconds that's why firstly I have converted in seconds and then used the below method.
$Date = date('m-d-Y H:i:s', 1615958170523/1000);
It always returns the time ~6hours ago i.e 03-17-2021 05:16:10 (Considering current time here), I don't want to add +5:30 hours to do the same.
Is it possible that we can use a standard method that means in-built functions which may be provided by Cakephp or PHP so that I can get the answer for the same?
I have also tried this one:
$gmtTimezone = new \DateTimeZone('GMT');
$myDateTime = new \DateTime(1615958170523/1000, $gmtTimezone);
It returns the same as I have used the date function.
You need to change the timezone after to define the timestamp in GMT.
$timestamp = 1615958170523/1000;
$myDateTime = \DateTime::createFromFormat('U', (int)$timestamp);
echo $myDateTime->format('Y-m-d H:i:s'), PHP_EOL; // 2021-03-17 05:16:10
$myDateTime->setTimezone(new \DateTimeZone('Europe/Paris'));
echo $myDateTime->format('Y-m-d H:i:s'), PHP_EOL; // 2021-03-17 06:16:10
$myDateTime->setTimezone(new \DateTimeZone('America/Denver'));
echo $myDateTime->format('Y-m-d H:i:s'), PHP_EOL; // 2021-03-16 23:16:10
See DateTime::setTimezone() documentation
You should use the FrozenTime which will use the default Timezone you set in your config/app.php
I'm programming a site about genealogy, I used the date input to acquire dates, and
$datamm= strftime('%Y-%m-%d', strtotime($_POST['datamm']));
to convert the dates for the database, but the minimum value that I can get is 1970-01-01. I need to acquire dates between 1500 and current day.
What can I do to solve the problem?? I prefer procedural solution if it is possible.
Here is an example,
<?php
$date = new DateTime( '01-01-1950' );
echo $date->format( 'Y-m-d' );
?>
DateTime is great, you can do all sorts once you understand it.
For instance, this will add a year and echo the start and end dates,
<?php
$date = new DateTime( '01-01-1950' );
echo $date->format( 'Y-m-d' )."\n";
$date->modify( '+1 years' );
echo $date->format( 'Y-m-d' );
?>
If you know that in which format your date is coming from input then you can try:
$datamm = DateTime::createFromFormat('j-M-Y', $_POST['datamm']);//You know that date is coming in j-M-Y format
echo $date->format('Y-m-d'); // You can save in Y-m-d format in database
if you are taking timestamp as input then :
$date = date('Y-m-d',$_POST['datamm']);//you are taking timestamp like : 30000000000 as an input
echo $date;//make in database in Y-m-d format
I hope it helps
Try this, use createFromFormat
// pass your date format
$date = DateTime::createFromFormat('d M Y','17 Jan 1500');
echo $date->format('Y-m-d');
DEMO
You should probably focus on using some 3rd party library instead of official PHP's datetime functions.
For example, for your advanced date-time manipulating requirements, a good alternative for PHP's standard datetime would be moment.php
It's inspired by moment.js library whose goal is to fix common date-time programming issues, and bring standardization to higher level.
You can obtain it via composer like:
{
"require": {
"fightbulc/moment": "*"
}
}
Or via github for manual installation.
To parse various input date consult a manual, below is example:
$m = new \Moment\Moment('1503-04-25T03:00:00', 'CET');
There is also other alternatives to explore, for example:
https://github.com/swt83/php-date
I'm developing a PHP project and I'm using Parse SDK. What i want to do is adjust the time given by the Parse Database. It gives me time and date that 8 hours late to my timezone. Here's the code I'm using :
$query = new ParseQuery("TestObject");
$query->get("xWMyZ4YEGZ");
$dateTime = $query->getCreatedAt();
$sched = $dateTime->format("M d, Y - hA");
echo $sched;
How can i adjust it to specifically "GMT+8" TimeZone? Thanks!
You have to set the date_default_timezone_set before doing any thing as:
if(function_exists('date_default_timezone_set'))
date_default_timezone_set($timezone);
List of timezones are provided here...
Have a look at PHP date with TZ - See N.B.'s answer here is a code snippet he suggests (you may be able to use the parse date instead of the "now" parameter):
<?php
$tz = 'Europe/London';
$timestamp = time();
$dt = new DateTime("now", new DateTimeZone($tz)); //first argument "must" be a string
$dt->setTimestamp($timestamp); //adjust the object to correct timestamp
echo $dt->format('d.m.Y, H:i:s');
I need a date object that has a time of 12:00:00am for the current day (meaning no seconds). I am converting that to that to the number of seconds and passing it in another function. It is eventually used for a report filter using date = "someDateHere' off the database, and the hanging seconds in the field are screwing up the report.
I'm not sure what to put in the second parameter in the time function - leaving it blank will use the current time, which is what I do not want. I can't find examples or anything in the php doc. If there is another function that will do the job, I am open to suggestions. This should be simple, but it is alluding me.
date_default_timezone_set('America/Detroit');
$now = date("Y-m-d 0:0:0");
echo $now . '<br/>';
$now = time($now,0);
echo $now . '<br/>';
Thanks in advance.
edit: Please note: I need to convert that date object to seconds. That is where the timestamp is screwing me up with strtotime function and time function. Even though I am passing it a dateobject without a timestamp, converting it into seconds not-so-conveniently is inserting the timestamp as the second parameter which defaults to the current time.
There are lots of available options here, since PHP accepts a wide variety of time formats.
$midnight = strtotime('midnight');
$midnight = strtotime('today');
$midnight = strtotime('12:00am');
$midnight = strtotime('00:00');
// etc.
Or in DateTime form:
$midnight = new DateTime('midnight');
$midnight = new DateTime('today');
$midnight = new DateTime('12:00am');
$midnight = new DateTime('00:00');
// etc.
See time formats and relative formats in the manual for a complete list of formats with descriptions.
Oh, I'd stop using those functions entirely, and start taking advantage of the DateTime class!
$date = new DateTime("now", new DateTimeZone("America/Detroit"));
echo $date->format("Y-m-d");
http://php.net/manual/en/class.datetime.php
time() takes no arguments. what you're doing is pointless. why not just strtotime(date('Y-m-d')) to get the unix timestamp for midnight?
i think mktime() is just what you need http://www.php.net/manual/en/function.mktime.php
<?php
// Set the default timezone to use. Available as of PHP 5.1
date_default_timezone_set('UTC');
// Prints: July 1, 2000 is on a Saturday
echo "July 1, 2000 is on a " . date("l", mktime(0, 0, 0, 7, 1, 2000));
// Prints something like: 2006-04-05T01:02:03+00:00
echo date('c', mktime(1, 2, 3, 4, 5, 2006));
?>