PHP UTC String to date - php

I have a problem. In my code I have the following line:
$RunDateTimeGMT0 = "2017-12-31 23:00:00";
The goal is to get the previous and next hour, so I tried this:
$RunDateTimeGMT0 = "2017-12-31 23:00:00";
$epochRunDateTimeGMT0 = strtotime($RunDateTimeGMT0);
$previousEpochDateTimeGMT0 = $epochRunDateTimeGMT0 - 3600;
$nextEpochDateTimeGMT0 = $epochRunDateTimeGMT0 + 3600;
But then the I get the following result:
previousEpochDateTimeGMT0 -> 2017-12-31 21:00:00
nextEpochDateTimeGMT0 -> 2017-12-31 23:00:00
Because of my timezone (+1) the RunDateTimeGMT0 gets converted to a date of my timezone.
I want the following result:
validEpochDateTimeGMT0 -> 2017-12-31 22:00:00
nextEpochDateTimeGMT0 -> 2018-01-01 00:00:00
How can I keep the date object UTC?

You can use the Carbon library. after import this library you should parse the date with this :
$RunDateTimeGMT0 = "2017-12-31 23:00:00";
$epochRunDateTimeGMT0 = Carbon::parse($RunDateTimeGMT0);
in this link, you could see the documentation of Carbon. Although, maybe you should to use this method :
$previousEpochDateTimeGMT0 = $epochRunDateTimeGMT0->addminutes(60);
$nextEpochDateTimeGMT0 = $epochRunDateTimeGMT0->subminutes(60);
I hope your problem solve with these lines, If another issue occurred you can ask.

#Ebrahim Bashirpour already shared a way of doing this by using the Carbon library but you can also do this by just using the PHP Datetime class. It supports both add time and subtracts time in seconds. Take a look at the DateTime documentation for more details.
<?php
$RunDateTimeGMT0 = "2017-12-31 23:00:00";
$date = new \DateTime($RunDateTimeGMT0);
$date->add(new \DateInterval('PT3600S')); //add 3600s / 1 hour
$next_epoc = $date->format('Y-m-d H:i:s'); // 2018-01-01 00:00:00
$date = new \DateTime($RunDateTimeGMT0);
$date->sub(new \DateInterval('PT3600S'));//add 3600s / 1 hour
$previous_epoc = $date->format('Y-m-d H:i:s'); //2017-12-31 22:00:00
var_dump($next_epoc);
var_dump($previous_epoc);
?>

Related

How to correctly add a date and a time (string) in PHP?

What is the "cleanest" way to add a date and a time string in PHP?
Albeit having read that DateTime::add expects a DateInterval, I tried
$date = new \DateTime('17.03.2016');
$time = new \DateTime('20:20');
$result = $date->add($time);
Which was no good and returned nothing to $result.
To make a DateInterval from '20:20', I only found very complex solutions...
Maybe I should use timestamps?
$date = strtotime($datestring);
$timeObj = new \DateTime($timestring);
// quirk to only get time in seconds from string date
$time = $timeObj->format('H') * 3600 + $timeObj->format('i') * 60 + $timeObj->format('s');
$datetime = $date+$time;
$result = new \DateTime;
$result->setTimestamp($datetime);
In my case, this returns the desired result, with the correct timezone offset. But what do you think, is this robust? Is there a better way?
If you want to add 20 hours and 20 minutes to a DateTime:
$date = new \DateTime('17.03.2016');
$date->add($new \DateInterval('PT20H20M'));
You do not need to get the result of add(), calling add() on a DateTime object will change it. The return value of add() is the DateTime object itself so you can chain methods.
See DateInterval::__construct to see how to set the intervals.
DateTime (and DateTimeImmutable) has a modify method which you could leverage to modify the time by adding 20 hours and 20 minutes.
Updated
I've included examples for both DateTime and DateTimeImmutable as per the comment made, you don't need to assign the outcome of modify to a variable because it mutates the original object. Whereas DateTimeImmutable creates a new instance and doesn't mutate the original object.
DateTime
<?php
$start = new DateTimeImmutable('2018-10-23 00:00:00');
echo $start->modify('+20 hours +20 minutes')->format('Y-m-d H:i:s');
// 2018-10-23 20:20:00
Using DateTime: https://3v4l.org/6eon8
DateTimeImmutable
<?php
$start = new DateTimeImmutable('2018-10-23 00:00:00');
$datetime = $start->modify('+20 hours +20 minutes');
var_dump($start->format('Y-m-d H:i:s'));
var_dump($datetime->format('Y-m-d H:i:s'));
Output
string(19) "2018-10-23 00:00:00"
string(19) "2018-10-23 20:20:00"
Using DateTimeImmutable: https://3v4l.org/oRehh

php - Parse.com change createdAt Column timezone

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');

Creating timestamp for 5/13/2014 # 3pm

I have an application that needs to send a UTC timestamp in order for it to work correctly. In my application a user can have any number of timezones. So if they pick 3pm and their timezone is America/New_York, it is a different 3pm than if it was America/Chicago.
I need to figure out a way to change the date into the right UTC timestamp. I know I can use date_default_timezone_set("UTC")...but I don't think will work correctly.
I think I need to calculate a difference between UTC and regular timezone, but I am not sure. Any advice is welcomes.
date_default_timezone_set("UTC");
echo strtotime('5/13/2014 3:00 PM');
1399993200
date_default_timezone_set("America/New_York");
echo strtotime('5/13/2014 3:00 PM');
1400007600
As you can tell these 2 values are different.
EDIT: Here is what my code looks like. It doesn't seem to work correctly as the application doesn't show the event in the right time.
$previous_timezone = date_default_timezone_get();
date_default_timezone_set("UTC");
$aceroute_schedule = $this->sale_lib->get_send_to_aceroute_schedule();
if (($start_time = strtotime($aceroute_schedule['aceroute_schedule_date']. ' '.$aceroute_schedule['aceroute_schedule_time_start'])) !== FALSE)
{
//Append 000 as as string for 32 bit systems
$start_epoch = $start_time.'000';
$end_epoch = strtotime('+ '.$aceroute_schedule['aceroute_duration'].' minutes', $start_time).'000';
}
else //Default to current time + 1 hour
{
//Append 000 as as string for 32 bit systems
$start_epoch = time().'000';
$end_epoch = strtotime('+1 hour', time()).'000';
}
$event->start_epoch = $start_epoch;
$event->end_epoch = $end_epoch;
Update:
This will now create a DateTime object in the user's DateTimeZone ('America/New_York'). And then it will set that object's timezone to UTC. To get the timestamp (or other string representations of date), use ::format().
# Create NY date
$NY = new DateTimeZone("America/New_York");
$NYdate = new DateTime('5/13/2014 3:00 PM', $NY);
# Set timezone to UTC
$UTC = new DateTimeZone("UTC");
$UTCdate = $NYdate->setTimezone($UTC);
# Get timestamp (PHP 5.2 compatible)
$timezone = $UTCdate->format('U');
var_dump($timezone); // a string containing UNIX timestamp
First I create 2 DateTime objects based off of their respective DateTimeZone objects. Then we can either use OOP ::diff() to get another object containing information about the time difference. Or we can use simple integers representing the difference in seconds from ::getTimestamp.
$date = '5/13/2014 3:00 PM';
# Create NY date
$NY = new DateTimeZone("America/New_York");
$NYdate = new DateTime($date, $NY);
# Create UTC date
$UTC = new DateTimeZone("UTC");
$UTCdate = new DateTime($date, $UTC);
# Find difference object
$diff = $NYdate->diff($UTCdate);
var_dump($diff); // a DateInterval object containing time difference info
# Find difference in seconds
$diff = $NYdate->getTimestamp() - $UTCdate->getTimestamp();
var_dump($diff); // an integer containing time difference in seconds
Links:
DateTimeZone
DateTime
DateInterval
Example in http://www.php.net/manual/en/datetime.settimezone.php
$date = new DateTime('2000-01-01', new DateTimeZone('Pacific/Nauru'));
echo $date->format('Y-m-d H:i:sP') . "\n";
$date->setTimezone(new DateTimeZone('Pacific/Chatham'));
echo $date->format('Y-m-d H:i:sP') . "\n";
The first line creates a DateTIme object, using the timezone Pacific/Nauru.
You can then change the timezone using setTimezone as shown in line 4, and the output will be modified accordingly.
note: the default timezone (if you don't specify it in the 2nd parameter in line 1) is the one set in your php.ini file, which you can modify (at runtime) with date_default_timezone_set("America/New_York")
note2: the 1st parameter in line 1, is equivalent to the 1st parameter of the strtotime function.
note3: the format method takes the same format parameter as date (http://www.php.net/manual/en/function.date.php)

How to extend date in PHP?

I have developed a subscription website. I am facing php date extend problem.
Please read my message-
Suppose today i have subscribe a package. Package duration 1 month. I mean 2014-05-08 to 2014-06-07
After two days i will again subscribe this same package. now the Package duration will extend 2014-06-07 to 2014-07-07
In my PHP code i am getting current date to +1 month but how to get after 1 month to next one month?
I have used this code:
date('Y-m-d h:i:s', mktime(0, 0, 0, date("m")+$getSubscription['Subscription']['duration'], date("d"), date("Y")));
You can use strtotime to achieve this.
Check this out:
<?php
// current subscription expiry date
$day = '2014-06-07';
// add 30 days to the date above
$new_date = date('Y-m-d', strtotime($day . " +30 days"));
// debug
echo $new_date;
Outputs: 2014-07-07
P.s. are you saving the newly calculated date into db or something and then using it on the next calculation?
Or use the DateTime object :
<?php
$date = new DateTime('2014-06-07');
$date_end = clone $date;
$date_end->add(new DateInterval('P1M');
echo $date_end->format('Y-m-d');
You'd save yourself a lot of hassle by using DateTime objects instead of messing around with date() and mktime(). In order to get today, simply:
$subscriptionDate = new DateTime(); // 2014-05-08
Then you can use the DateInterval class to add additional months, so if it's a monthly subscription, simply:
$subscriptionPeriod = new DateInterval('P1M');
$subscriptionDate->add($subscriptionPeriod);
Now, $subscriptionDate will be at 2014-06-08. You can keep adding as many months as you want and save it to your database, in the format you want, like:
$subscriptionDate->format('Y-m-d'); // 2014-06-08
$subscriptionDate->format('Y-m-d H:i:s'); // incl. time, e.g. 2014-06-08 12:02:45
See the manual for more examples.

timestamp function Pluse 1 hour PHP

I am tring to get a set time timestamp for e.g
if I input the follow time 09:00 i want to see the timestamp for today
function GetTimestamp($time){
date();
}
return GetTimestamp("09:00")
can someone help me please or lead me down the right path
You just have to use the strtotime() function, passing it your time :
$ts = strtotime('09:00');
var_dump($ts);
And you'll get :
int 1300435200
Note : if you don't specify the date, strtotime will use today.
You could also use the DateTime class :
$dt = new DateTime('09:00');
$ts = $dt->format('U');
var_dump($ts);
Use strtotime:
$timestamp = strtotime('09:00');

Categories