How to set time with timezone? - php

In my project time shows as
"2017-01-01 12:00:00+03:00".
How to make it as
"2017-01-01 15:00:00"
?

You can use like this
echo date("Y-m-d H:i:s A",strtotime('2017-01-01 12:00:00+03:00'));
But you will get 09:00:00 AM not 15:00:00 AM because your time is +3 ahead
https://eval.in/822865

Your time 2017-01-01 12:00:00+03:00 means that it is hour 12:00:00 in the timezone of +3 hours. You don't want to do anything just to reformat your time to different display:
(new DateTime($yourDateInStringOrUnix))->format('Y-m-d H:i:s');
and you will get
`2017-01-01 12:00:00` //This is local time in timezone of +3 hour

You want to add offset to your current time. Separate datetime with offset and recalculate it.
<?php
date_default_timezone_set('UTC');
$date = '2017-01-01 12:00:00+03:00';
$datetime = substr($date, 0, 19); // Get date time string
$offset = substr($date, 19); // Extract Offset
list($hours, $minutes) = explode(':', $offset);
$seconds = $hours * 60 * 60 + $minutes * 60; // Convert offset to seconds
// Recalculate date time by adding offset
echo date('Y-m-d H:i:s', strtotime($datetime) + $seconds);
?>
Output
2017-01-01 15:00:00
Hope this helps!

You can make it like this.
If this is coming from your data you can do it like this:
$my_date = "2017-01-01 12:00:00+03:00";
$converted_date = date('Y-m-d H:i:s', strtotime($my_date));
echo $converted_date;
But if you are getting the current date and time only you can make it this way;
$my_date = date('Y-m-d H:i:s');
echo $my_date;

Related

How to Display Current date+current time + 1 hour in text box in php [duplicate]

I currently have php returning the current date/time like so:
$now = date("Y-m-d H:m:s");
What I'd like to do is have a new variable $new_time equal $now + $hours, where $hours is a number of hours ranging from 24 to 800.
Any suggestions?
You may use something like the strtotime() function to add something to the current timestamp. $new_time = date("Y-m-d H:i:s", strtotime('+5 hours')).
If you need variables in the function, you must use double quotes then like strtotime("+{$hours} hours"), however better you use strtotime(sprintf("+%d hours", $hours)) then.
An other solution (object-oriented) is to use DateTime::add
Example:
<?php
$now = new DateTime(); //now
echo $now->format('Y-m-d H:i:s'); // 2021-09-11 01:01:55
$hours = 36; // hours amount (integer) you want to add
$modified = (clone $now)->add(new DateInterval("PT{$hours}H")); // use clone to avoid modification of $now object
echo "\n". $modified->format('Y-m-d H:i:s'); // 2021-09-12 13:01:55
Run script
DateTime::add PHP doc
DateInterval::construct PHP doc
You can use strtotime() to achieve this:
$new_time = date("Y-m-d H:i:s", strtotime('+3 hours', $now)); // $now + 3 hours
Correct
You can use strtotime() to achieve this:
$new_time = date("Y-m-d H:i:s", strtotime('+3 hours', strtotime($now))); // $now + 3 hours
You can also use the unix style time to calculate:
$newtime = time() + ($hours * 60 * 60); // hours; 60 mins; 60secs
echo 'Now: '. date('Y-m-d') ."\n";
echo 'Next Week: '. date('Y-m-d', $newtime) ."\n";
Um... your minutes should be corrected... 'i' is for minutes. Not months. :) (I had the same problem for something too.
$now = date("Y-m-d H:i:s");
$new_time = date("Y-m-d H:i:s", strtotime('+3 hours', $now)); // $now + 3 hours
I use this , its working cool.
//set timezone
date_default_timezone_set('GMT');
//set an date and time to work with
$start = '2014-06-01 14:00:00';
//display the converted time
echo date('Y-m-d H:i',strtotime('+1 hour +20 minutes',strtotime($start)));
for add 2 hours to "now"
$date = new DateTime('now +2 hours');
or
$date = date("Y-m-d H:i:s", strtotime('+2 hours', $now)); // as above in example
or
$now = new DateTime();
$now->add(new DateInterval('PT2H')); // as above in example
You can try lib Ouzo goodies, and do this in fluent way:
echo Clock::now()->plusHours($hours)->format("Y-m-d H:m:s");
API's allow multiple operations.
For a given DateTime, you can add days, hours, minutes, etc. Here's some examples:
$now = new \DateTime();
$now->add(new DateInterval('PT24H')); // adds 24 hours
$now->add(new DateInterval('P2D')); // adds 2 days
PHP: DateTime::add - Manual https://www.php.net/manual/fr/datetime.add.php
$to = date('Y-m-d H:i:s'); //"2022-01-09 12:55:46"
$from = date("Y-m-d H:i:s", strtotime("$to -3 hours")); // 2022-01-09 09:55:46
$date_to_be-added="2018-04-11 10:04:46";
$added_date=date("Y-m-d H:i:s",strtotime('+24 hours', strtotime($date_to_be)));
A combination of date() and strtotime() functions will do the trick.
$now = date("Y-m-d H:i:s");
date("Y-m-d H:i:s", strtotime("+1 hours $now"));

How to Subtract Minutes

I want to send a reminder email.I don't want to use cron on Linux/Unix/BSD box or Scheduled Tasks on Windows.
I'm trying to subtract 15 minutes from the current time.
here is my code so far (doesn't work):
$days = date("j",time());
$months = date("n",time());
$years = date("Y",time());
$hours = date("G",time());
$mins = (date("i",time()));
$secs = date("s",time());
$mins = $mins-15;
To subtract 15 minutes from the current time, you can use strtotime():
$newTime = strtotime('-15 minutes');
echo date('Y-m-d H:i:s', $newTime);
Change the date into a timestamp (in seconds) then minus 15 minutes (in seconds) and then convert back to a date:
$date = date("Y-m-d H:i:s");
$time = strtotime($date);
$time = $time - (15 * 60);
$date = date("Y-m-d H:i:s", $time);
You can use DateInterval
$date = new DateTime();
$interval = new DateInterval("PT15M");
$interval->invert = 1;
$date->add($interval);
echo $date->format("c") . "\n";
you can try this as well,
$dateTimeMinutesAgo = new DateTime("15 minutes ago");
$dateTimeMinutesAgo = $dateTimeMinutesAgo->format("Y-m-d H:i:s");
How about substracting the 15 minutes from time() before converting it?
$time = time() - (15 * 60);
And then use $time instead of time() in your code.
$currentTime = date('Y-m-d H:i:s');
$before15mins = strtotime('-15 minutes');
echo date('Y-m-d H:i:s', $before15mins);
You can also use strtotime function to subtract days, hours and/or seconds from current time.
echo date('Y-m-d H:i:s', strtotime('-15 minutes'));
Following is the way you can add days / hours / minutes / sec to current time
$addInterval = date('Y-m-d H:i:s', strtotime("+$days days $hours hours $minute minute $sec second", strtotime(currentTime)));
You can also use DateInterval object
<?php
$date = new DateTime('Y-m-d H:i:s');
$date->sub(new DateInterval('PT10H30S'));
echo $date->format('Y-m-d H:i:s');?>
Try using
$min = time() - 900; //900 seconds = 15 minutes
To subtract 15 minutes you can do:
date('Y-m-d H:i:s', (time() - 60 * 15));
You can replace 15 with the number of minutes you want.
In case you're looking to subtract seconds you can simply do:
date('Y-m-d H:i:s', (time() - 10));
In this way you'll subtract 10 seconds.
If you have only time value than below will be useful
// Your time
$time = '12:15:00';
// Returned value '12:00:00'
$newTime = date('H:i:s', strtotime($time) - (15*60));
I know this question is outdated but i just want to share how i did it in easy way
$current = new DateTime("10 minutes ago", new DateTimeZone('Asia/Manila') );
echo $current->format("Y-m-d H:i:s");
//To Get Current DateTime
$currentDate = date("Y-m-d H:i:s");
//To Get Current DateTime - 15Min
$oldDate = date("Y-m-d H:i:s", strtotime($currentDate) - (15 * 60));
echo $currentDate;
echo $oldDate;

Round datetime to last hour

I tried to look for this but I could not find good example of this what im trying to do.
I got datetime values in MySQL database that has to be rounded down when that value is on use.
Example, all these values:
2013-04-20 07:14:42
2013-04-20 07:19:51
2013-04-20 07:37:26
2013-04-20 07:46:28
2013-04-20 07:59:44
Should be rounded down to:
2013-04-20 07:00:00
And
2013-04-20 16:25:34
should be:
2013-04-20 16:00:00 etc...
PHP code that gets date value:
$d = strtotime($row["date"]);
So, how its possible to round down datetime value?
Try this,
$date = "2013-04-20 16:25:34";
echo date("Y-m-d H:00:00",strtotime($date));
CodePad Demo.
If you are using PHP's Carbon DateTime library (which you really should - https://github.com/briannesbitt/Carbon )
You can achieve it easily using
Carbon::now()->minute(0)->second(0);
Since you already have a Unix timestamp $d, most efficient way is to use only arithmetic instead of date functions - especially if you're going to loop through a result set.
$hourTimestamp = $d - ($d % 3600);
Modulo operator gives you the remainder which you subtract from the timestamp to get hour timestamp.
In that case a simple substr could do:
echo substr($date, 0, 13) . ":00:00";
Refering to #Dayson response, this is a better way to round datetime to last hour with Carbon
$dt = Carbon::create(2012, 1, 31, 15, 32, 45);
echo $dt->startOfHour(); // 2012-01-31 15:00:00
check the Modifier section in Carbon Doc
For those who follow (much later!): Carbon has an easy way to do this
$date = (new Carbon($row['date']))->minute(0)->second(0)->getTimestamp();
you can use
date and strtotime function function to achieve this, simply already change your minutes and second accordling
$date = '2013-04-20 07:14:42';
$newdate = date('Y-m-d H:00:00', strtotime($date));
echo $newdate;
this will output
2013-04-20 07:00:00
This writes the date to a string by outputting directly 00:00 as minutes and seconds instead of writing i:s:
$date = date("Y-m-d H:00:00", $d);
Or do you need it as unix timestamp? Then cut the minutes and the seconds off (always the last 5 bytes) and replace them by 00:00.
$d = strtotime(substr($row["date"], 0, -5)."00:00"));
strtotime() gives you a Unix timestamp which is the number of seconds since 1970-01-01 00:00:00.
What if just divided by 3600 seconds (seconds equivalent to 1 hour) and ignore the remainders (the minutes and seconds you do want)?
$d = strtotime($row["date"]);
$rounded_d = intval($d / 3600);
$formatted_rounded_d = date('Y-m-d H:i:s', $rounded_d)
I would use DateTime's setTime() method in a function like this.
<?php
/**
* #param \DateTime $dateTime
*
* #return \DateTime
*/
function roundDownToHour(\DateTime $dateTime)
{
$dt = $dateTime; // clone
return $dt->setTime(
$dateTime->format("H"),
0,
0
);
}
$testDate = date("Y-m-d H:i:s", mktime(9, 59, 59, 1, 30, 2019));
$roundedDownToHour = roundDownToHour(new \DateTime($testDate));
var_dump($testDate); //=> 2019-01-30 9:59:59
var_dump($roundedDownToHour->format("Y-m-d H:i:s")); //=> 2019-01-30 09:00:00
Which results to the following.
// the results
string(19) "2019-01-30 09:59:59"
string(19) "2019-01-30 09:00:00"
It's important you use a built-in PHP function for rounding times to take into account the date as well as the time. For example 2020-10-09 23:37:35 needs to become 2020-10-10 00:00:00 when rounding up to nearest hour.
Round time to nearest hour:
$time = '2020-10-09 23:37:35';
$time = date("Y-m-d H:i:s", round(strtotime($time) / 3600) * 3600); // 2020-10-10 00:00:00
$time = '2020-10-09 23:15:35';
$time = date("Y-m-d H:i:s", round(strtotime($time) / 3600) * 3600); // 2020-10-09 23:00:00
Round time to nearest 20 minute increment:
$time = '2020-10-09 23:15:35';
$time = date("Y-m-d H:i:s", ceil(strtotime($time) / (60*20))*(60*20)); // 2020-10-09 23:20:00
$time = '2020-10-09 23:41:35';
$time = date("Y-m-d H:i:s", ceil(strtotime($time) / (60*20))*(60*20)); // 2020-10-10 00:00:00
If you need to round down to nearest 20 minute increment, change ceil to floor e.g
$time = date("Y-m-d H:i:s", floor(strtotime($time) / (60*20))*(60*20)); // 2020-10-09 23:40:00
If you need to round time to another minute increment you can simply do:
$time = date("Y-m-d H:i:s", ceil(strtotime($time) / (60*15))*(60*15)); // 2020-10-09 23:45:00

PHP - Strtotime - Add hours

I have this variable:
$timestamp = strftime("%Y-%m-%d %h:%M:%S %a", time ());
I simply want to add three hours and echo it out.
I have seen the way where you can do the 60 * 60 * 3 method or the hard code "+ 3 hours" where it understands the words.
What is the best way of getting this result?
The best way is what you think is more readable. The following expressions are identical:
time() + 3 * 60 * 60
strtotime('+3 hours')
i always do like this
$current_time = date('Y-m-d H:i:s');
$new_time = strtotime($current_time . "+3hours");
echo $new_time;
or
$new_time = mktime(date('H')+3, 0, 0, date('m'), date('d'), date('Y'));
$new_time = date('Y-m-d H:i:s', $new_time);
echo $new_time;
$timestamp = strftime("%Y-%m-%d %h:%M:%S %a", time() + 3*60*60)
3*60*60 is the best way
Just add seconds to add hours:
strtotime($your_date)+2*60*60
This will add two hours in your date.
You can use DateTime::modify to add time, but I would just do time()+10800.
$time = new DateTime("+ 3 hour");
$timestamp = $time->format('Y-M-d h:i:s a');
Clear and concise :)
If you want to go 'modern':
$d = new DateTime();
$d->add(new DateInterVal('P3H'));
$timestamp = $d->format('Y-M-d h:i:s a');
refs: DateTime object

How to increment date with 1 (day/year) in PHP?

I have a date stored in an array:
$this->lines['uDate']
The format of the date is not fixed. I can be changed with this:
define('DATETIME_FORMAT', 'y-m-d H:i');
How can I increment my uDate with a certain number of days or years?
My question is related to this one:
increment date by one month
However, in my case the date format in dynamic.
So, can I do this?
$time= $this->lines['uDate'];
$time = date(DATETIME_FORMAT, strtotime("+1 day", $time));
$this->lines['uDate']= $time;
date_add()
and consider changes like:
define(DATETIME_FORMAT, 'y-m-d H:i');
$time = date(DATETIME_FORMAT, strtotime("+1 day", $time));
You can use some simple calculation to do it if you have the timestamp.
$date = strtotime($this->lines['uDate']); //assuming it's not a timestamp\
$date = $date + (60 * 60 * 24); //increase date by 1 day
echo date('d-m-y', $date);
$date = $date + (60 * 60 * 24 * 365); //increase date by a year
echo date('d-m-y', $date);
You can also use the mktime() method to do this : http://php.net/manual/en/function.mktime.php
function add_date($givendate,$day=0,$mth=0,$yr=0)
{
$cd = strtotime($givendate);
$newdate = date('Y-m-d h:i:s', mktime(date('h',$cd),
date('i',$cd), date('s',$cd), date('m',$cd)+$mth,
date('d',$cd)+$day, date('Y',$cd)+$yr));
return $newdate;
}
I have found this in PHP help
another useful way, if you want an object rather than a string:
$date = DateTimeImmutable::createFromFormat('Y-m-d', '2022-01-05'); // just an exemplary date
$date = $date->add(date_interval_create_from_date_string('1 day')); // count up
notable difference:
date_add() changes the original object, while DateTimeImmutable::add() does not and simply returns the new object. Depending on the desired behavior, use one or the other.

Categories