PHP timezone only changing part of the times - php

I am trying to display an event time in three different timezones, so I set the time in a text field ("2:00 pm") with by default is EDT, and the output should be:
2:00 pm EDT / 1:00 pm CDT / 11:00 am PDT
But instead it's just showing as:
2:00 pm EDT / 2:00 pm CDT / 2:00 pm PDT
So, the times are not converting, but the timezone is. Here is my code:
// Get the value from the text field
$value = '2:00 pm';
// Let's first check to see if the value is a valid time
if( strtotime( $value ) ){
// Let's convert the time into an actual time, using today's date as filler
date_default_timezone_set( 'America/New_York' );
$time = date( 'Y-m-d g:i:s a', strtotime( 'today '.$value ) );
// List the timezones we want to return
$timezones = [
'US/Eastern',
'America/Chicago',
'America/Los_Angeles',
];
// Empty array
$display = [];
// Cycle through each timezone
foreach( $timezones as $timezone ) {
// Let's set the timezone
date_default_timezone_set( $timezone );
// Get the time in the new timezone
$new_time = date( 'g:i a T', strtotime( $time ) );
// Make the initials lowercase for the class
$ini = strtolower( date( 'T', strtotime( $value ) ) );
// Add the time to the array
$display[] = '<span class="'.$ini.'-time">'.$new_time.'</span>';
}
// Return all of the times from the array
return implode(' <span class="sep-time">/</span> ', $display );
} else {
// Else state it's not valid
return '<strong>INVALID TIME FORMAT - PLEASE USE "H:MM AM/PM"</strong>';
}
You can see that I'm getting the timezone initials (EDT, CDT, PDT) from the date() function, which all change just fine, but the actual times are not. I tried switching to 'H:i' instead of 'g:i', but it just changes to 7pm, 6pm and 4pm, which are all 5 hours ahead.

my way to change timzones:
$time = new DateTime("now", new DateTimeZone("UTC");
$time->setTimezone(new DateTimeZone("US/Eastern")); // now it's US/Eastern
$time->setTimezone(new DateTimeZone("America/Chicago")); // now it's America/Chicago
make sure you type hint:
use DateTime, DateTimeZone;

Related

PHP convert the day date with the time

I am working on my php script to set up the date with the time. I need some help with convert the day date to the current day and next day date, example: my current time is 15:27 and my current date is 27-11-2019 so when I have the string for the variable get_time1 is 06:00:00, I want to convert it to 28-11-2019 06:00:00. When I have the variable get_time2 that have the time which it is 23:00:00 as my current time is before 23:00:00 so i want to convert the date with the current date with the time to 27-11-2019 23:00:00.
Code:
<?php
$get_time1 = '06:00:00';
$get_time2 = '23:00:00';
date_default_timezone_set('Europe/London');
$Date = date('Y-m-d');
$time = date('H:i:s');
?>
Can you please show me an example how I can set up the day date with the time 06:00:00 and 23:00:00 as if the time 06:00:00 is after 12am to set up the next day date and if the time 23:00:00 is before 12am then set up the time with the current date?
Thank you.
This just creates a DateTime object from the time (which will default it to todays date) and if this is less than the current date and time, it adds 1 day...
$date = DateTime::createFromFormat("H:i:s", $get_time2);
if ( $date < new DateTime() ) {
$date->modify("+1 day");
}
which gives
2019-11-27 23:00:00
and for $get_time1...
2019-11-28 06:00:00
If you use a DateTime that will allow you to do date arithmetic.
$now = new DateTime();
$tomorrow = $now->modify("+1 day");
You can also use strtotime to get a unix timestamp as explained in this answer.
$tomorrow = strtotime('+1 day');
maybe this will do?
$offset = timezone_offset_get( timezone_open( "Europe/London" ), new \DateTime() );
echo 'in London' . gmdate('d-m-Y H:i:s', date( "U" )+$offset);
echo 'current location: ' . date('d-m-Y H:i:s', date( "U" ));

How to subtract a decimal time from a clock time in PHP

I have the following PHP script:
<?php
$clockTime = "10:00 AM";
$decimalTime = "0.75"; // represents time in hours in decimal format
echo date( 'g:i A', strtotime( strtotime( $clockTime ) . ' -'.$decimalTime.' hours' ) ); // returns "7:00 PM" when I need it to return "9:15 AM"
?>
How can I get the script to properly calculate and return 9:15 AM rather than 7:00 PM?
strtotime returns the time in seconds, so you need to convert the decimal time in seconds:
<?php
date( 'g:i A', strtotime( $clockTime ) - $decimalTime * 60 * 60 ) );
?>
However, this will not work when daylight saving (DST) comes into play. Especially if your code will be run in different countries, use timezones and the DateTime-API:
<?php
$date = new \DateTime($clockTime); // This uses the system default timezone where the server is located
$date->sub(new \DateInterval('PT' . ((int) $decimalTime * 60 * 60) . 'S'));
echo $date->fomat('g:i A');
?>

daylight saving (London) issue in php: CI

I am trying to convert any timezone to LONDON timezone. At this moment the daylight concept is not considered.
When my time is : 07-04-2016 03:00 PM expected in LONDON is : 07-04-2016 10:30 AM
In my case it is : 07-04-2016 09:30 AM
Here is my php code in CI Helper:
function convert_datetime_to_utc_timezone($date, $timezone) {
if ($date != '') {
$ci = & get_instance();
$dformat .= "Y-m-d H:i:s";
$zone = get_list_of_all_timezone();
$user_time_zone = $zone[$timezone];
$convert_date = new DateTime($date, new DateTimeZone($user_time_zone));
$convert_date->setTimeZone(new DateTimeZone('UTC'));
return $convert_date->format('Y-m-d H:i:s');
} else {
return '';
}
}
Note: $user_time_zone = 'Asia/Calcutta';
If you want to convert your local time to London time, then please use 'Europe/London'. The general time zones like UTC, EST etc wouldn't consider day light saving time.
$your_date = date ( 'Y-m-d H:i:s', strtotime ( $your_date ) );
$newyork_time = new DateTime ( $your_date, new DateTimeZone ( 'America/New_York' ) );
$london_time = new DateTime ( $your_date, new DateTimeZone ( 'Europe/London' ) );
If you want London time, then set the timezone to 'Europe/London', not UTC.
$ php -a
Interactive mode enabled
php > $format = 'd-m-Y H:i A';
php > $input_timezone = 'Asia/Calcutta';
php > $input_datetime = '07-04-2016 03:00 PM';
php > $datetime = DateTime::createFromFormat($format, $input_datetime, new DateTimeZone($input_timezone));
php > $datetime->setTimeZone(new DateTimeZone('Europe/London'));
php > var_dump($datetime->format($format));
string(19) "07-04-2016 10:30 AM"

Find timestamp for the last 8am encountered?

I want to find the timestamp for the most recent 8am encountered. (weekdays only)
For example if its Friday at 3pm I want the timestamp for 8am.
I can do that simply enough, but what about if it is Saturday at 2am.
Also if it is Monday at 6am I want to find Friday at 8am still.
Tried the following:
$timestamp = strtotime(date('Y-m-d') . '08:00:00');
But clearly that only accounts for the current day.
This should do it:
// Choose today if it's past 08:00 and it's not a weekend
if( date( 'G' ) >= 8 && date( 'N' ) <= 5 ) {
$timestamp = strtotime( date( 'Y-m-d' ).' 08:00' );
}
else {
$timestamp = strtotime( 'last weekday 08:00' );
}

How to make a normal user input of time and date to get it added in mysql as timestamp?

In the user interface, i have a text field to enter date in dd/mm/yyyy format and there is another textbox for time in hh:mm format and another dropdown box to specify am or pm. All these three fields will let the user to enter the date,time and am/pm manually. I prefered to use this primitive method as per the requirement of the project.
Now i want all these values to be added in mysql in timestamp format to make it easier to fetch and manipulate. Please suggest me how can i achieve this.
<?
$date = '21'.'/'.'11'.'/'.'2011';
$time = '12'.':'.'00';
$ampm = "am";
$dt = DateTime::createFromFormat(
'd/m/Y h:i a',
sprintf('%s %s %s', $date, $time, $ampm),
new DateTimeZone('Country/Region'));
$mysqlDateString = $dt->format('Y-m-d H:i:s');
?>
Use mktime in conjunction with the correct format to date by sending your user input to explode, like so:
$date = '22/11/2011'; $date_pieces = explode( '/', $date);
$time = '08:35'; $time_pieces = explode( ':', $time);
$am_pm = 'PM';
$mysql_timestamp = date( 'Y-m-d H:i:s', mktime(
$time_pieces[0] + ( $am_pm == 'AM' ? -12 : 12), // Hour - Convert AM/PM to 24-hr format
$time_pieces[1], // Minute
0, // Second
$date_pieces[1], // Month
$date_pieces[0], // Day
$date_pieces[2])); // year
Now $mysql_timestamp is a valid entry for a datetime column.
If you need a UNIX timestamp, just remove the call to date, like so:
$unix_timestamp = mktime(
$time_pieces[0] + ( $am_pm == 'AM' ? -12 : 12), // Hour - Convert AM/PM to 24-hr format
$time_pieces[1], // Minute
0, // Second
$date_pieces[1], // Month
$date_pieces[0], // Day
$date_pieces[2]);
Demo
Edit: As per Phil's comments below, be sure to set a correct timezone with date_default_timezone_set.
Use DateTime::createFromFormat().
Assuming the form fields have been POSTed, roughly validated and collected into variables...
// assume $date, $time, $ampm
$dt = DateTime::createFromFormat(
'd/m/Y h:i a',
sprintf('%s %s %s', $date, $time, $ampm),
new DateTimeZone('Country/Region'));
$unixTimestamp = $dt->getTimestamp();
$mysqlDateString = $dt->format('Y-m-d H:i:s');
If you're storing the date/time as a MySQL date/time string, you should probably store the timezone as well or else it will be impossible to retrieve accurate data.
There is loads of information over at MySQL about time conversions. In your case I think str_to_date would work.

Categories