PHP Adding and Subtracting Time to a given timestamp - php

I get a timestamp from mysql like
2012-04-12 16:42:33
in PHP how can i subtract hours, or basically how can i change timezone (-3 hours)?

You should use PHP's DateTime. You can check out the supported formats and then create a new object:
$date=new DateTime("2012-04-12 16:42:33");
This object also supports changing timezones and other conversions. Setting a new timezone (from PHP manual):
$date->setTimezone(new DateTimeZone('Pacific/Chatham'));

strtotime('-3 hours', strtotime('2012-04-12 16:42:33'));
http://php.net/manual/en/function.strtotime.php
Changing timezones is technically a bit more tricky, since the way your timestamp is formatted, we don't know what timezone the original is in. So, this code should suffice.

$hours = 3;
$time_old = "2012-04-12 16:42:33";
$time_new = strtotime($time_old);
$time_new = $time_new - (60 * $hours);
date($time_new);
This will allow you to dynamically change the hours by changing $hours.

Related

Changing PHP default timezone not working

I am trying to have a line of code added to an html document that is preceded by the time. I want the time zone to be relative to me, however I cannot change it from the default UTC. I have changed in the php.ini file to PST as well as using date_default_timezone_set('America/Los_Angeles'); and yet it still prints the time 7 hours ahead of my timezone. Heres the code that deals with the time:
session_start();
if(isset($_SESSION['name']))
{
date_default_timezone_set('America/Los_Angeles');
$msg = $_POST['text'];
$fo = fopen("log.html", 'a');
fwrite($fo, "<div class=msgln>(".date("g:i A").") <b style=color:red;>".$_SESSION['name']."</b>: ".stripslashes(htmlspecialchars($msg))."<br></div>
");
fclose($fo);
}
Servers should be set to UTC, and you should not be looking to change the default. Instead, what you want to do is create a DateTime object based on the time, then convert it to the timezone you want, and display.
$now = new DateTime();
$now->setTimezone(new DateTimeZone('America/Los_Angeles'));
echo $now->format('g:i A');
I don't know if your format string is valid or not, but the format method is suppossed to be compatible with that accepted by the date() function you were using in your original example.
First make sure you're using a valued timezone. You can find a list of supported timezones in the PHP docs.
The second problem is using date() without specifying the timestamp. This defaults to the timestamp produced by time() which (based on a comment in the documentation) is UTC time. You'll either have to use strftime() or manually subtract the difference from UTC.
If you use 'etc/GMT' you can set the dateTime object to the desired time zone like so:
$dtz = new DateTimeZone('etc/GMT-10');
$dt = new DateTime(date("Y-m-d h:i A"), $dtz);
$date = gmdate("Y-m-d h:i A", $dt->format('U'));

Converting Date Format for Calculations in PHP

I'm displaying a due date for tasks in an m/d/y format. I'm displaying the day the task was posted in a "Posted X $name(s) ago" (eg. "Posted 6 day(s) ago").
I'm working on giving the timestamps (posted and due date) different CSS classes, depending on how many days there are from TODAY until the due date. (So the "Posted X" timestamp is less relevant, I just wanted to give a better picture.)
So far, I have the following down:
$cdate = $this->data['due'];
$today = time();
$dovi = date('m/d/Y', $today);
$difference = $cdate - $dovi;
$upcoming= floor($difference/60/60/24);
$cdate is pulling the due date from the DB, in m/d/y format. $today is telling us what today is (using the UNIX timestamp). $dovi is converting time() in to the m/d/y format. $difference is telling us the difference between today and the due date. $upcoming, in theory, should take that difference and dumb it down into a simple number.
I think that for the calculation to work, I would need to convert $cdate in to a UNIX timestamp or somehow convert both $today and $cdate into some other matching format other than m/d/y.
Does anyone have suggestions on the best way to make this work? I already have some code to run the CSS changes, the only thing I'm stuck on is this conversion/calculation issue to determine how many days from NOW (time()) the due date is. Thanks!!
Maybe something like this? Assuming $this->data['due'] is in m/d/Y format.
$this->data['due'] = '7/28/2012';
$diff = strtotime($this->data['due']) - strtotime(date('m/d/Y'));
var_dump(date('d',$diff)); // 3
You can pass any valid parameter to php's date function to have it formatted however you would like.
Its long one, but works...
$datetime = new DateTime("2012-07-22 02:03:50"); // your date in datetime type
$curr_stamp = time();
$act_stamp = mktime($datetime->format('H'), $datetime->format('i'), $datetime->format('s'), $datetime->format('n'), $datetime->format('j'), $datetime->format('Y'));
$diff=$curr_stamp-$act_stamp;
$day_diff = floor($diff / 86400);
if($day_diff < 7)
echo $day_diff." days ago";
Rather elegant and right solution (and also viable after the end of UNIX epoch).
$today = new DateTime(); // creating `today` DateTime object
$expiry = DateTime::createFromFormat('m/d/Y', $this->data['due']) // creating DateTime object from already formatted date
$difference = $today->diff($expiry); // 1st variant to calculate difference between dates
$difference = date_diff($today, $expiry); // and 2nd variant
echo $difference->format('Interval (difference) is %R% days');
Remember that UNIX epoch (timestamp) will "end" "soon" and code based on timestamps possibly will face some problems (maybe we will find the solution in future to avoid this, but ...), it is better to use DateTime class, bec. even to calculate number of years for those who are born before 1970 year can become kinda problem if you don't remember the date 1970.01.01 and trying to do it using timestamps (it is widespread database practice BTW :) ).
Never do it (timestamps) for very old dates and look to the future and DateTime will SaveOurSouls.

Remove time part of a timestamp

How can I remove time part of a timestamp?
So for example turn 1310571061 to 1310565600 which is the plain date timestamp.
strtotime(date("Y-m-d", 1310571061));
That should do it for you.
In case you wanted a mathematical solution:
$time=1310571061;
echo floor($time/86400)*86400;
There are 86,400 seconds in 24 hours (which is the length of a typical day, but not all... see DST). Since our timestamps are in UTC, this shouldn't be a problem. You can divide that by the number of seconds in a day, drop the remainder, and multiply back out.
Using a DateTime object can be helpful, and also can make the code more readable...
$dt = new DateTime();
$dt->setTimestamp(1310571061);
echo $dt->format('Y-m-d, H:i:s') . "\r\n";
$dt->setTime(0, 0, 0);
echo $dt->format('Y-m-d, H:i:s');
Result...
2011-07-14, 03:31:01
2011-07-14, 00:00:00
The choice of whether to use raw timestamps or DateTime objects will depend a lot on the implementation needs, but generally speaking DateTime objects will go a long way towards reducing confusion and errors that can crop up especially around Timezone issues and Daylight Saving Time issues.
Try:
<?php
$ts = '1310571061';
echo strtotime(date('Y-m-d 00:00:00', $ts));
?>
$pubdate='2003-02-19T00:00:00.000-05:00';
$da = strtotime($pubdate);
echo $dat = date('Y-m-d', $da);
The answer is like :"2003-02-19"
Thank You
You could do:
$date = strotime(date("y/m/d", $timestamp));
This is what I usually do:
your_timestamp = pd.to_datetime(your_timestamp.strftime(format="%x"))
The function strftime will convert your_timestamp to a string without the time component. Then the function pd.to_datetime will convert it back to a Timestamp without the time component.

Converting from UTC in PHP using a variable timezome

I store timestamps on my server using a simple timestamp in SQL. When I pull down that timestamp, I run it through the following function in order to format the time.
How do I add to the following function in order to convert $timestamp into whatever timezone the user is querying from?
// Returns the formatted time
function displayDate($timestamp)
{
$secAgo = time() - $timestamp;
// 1 day
if ($secAgo < 86400)
return date('h:i:A', $timestamp);
// 1 week
if ($secAgo < (86400 * 7))
return date('l', $timestamp);
// older than 1 week
return date('m/t/y', $timestamp);
}
If you have timezone name to change, you can use something like:
$date = new DateTime(date('Y-m-d H:i:s', $timestamp), new DateTimeZone('UTC'));
$date->setTimezone(new DateTimeZone('Asia/Vladivostok'));
return $date->format('m/t/y');
Where Asia/Vladivostok is the user's custom timezone.
#zerkms's method is the best way to convert timestamps to any timezone.
But if you do that every time you need to display a time, it may have a significant performance hit because you're setting up and tearing down a timezone object every time. There's a convenient shortcut, if all the timestamps on the page are going to be in the same timezone. (Which is usually the case, because users don't change timezones in the middle of an HTTP request.)
Somewhere outside of the function, do:
date_default_timezone_set('America/New_York'); // or any other timezone
It's probably a good idea to tie this into one of your session management functions, so that the same user always gets the same timezone.
Once you do this, date() will automatically start using the correct timezone, assuming that $timestamp represents a Unix timestamp. It will also automatically correct for daylight saving time. So there's no need to change anything in that function.
Use timezone_identifiers_list() to retrieve a list of valid timezones.

add one year to datetime with php

$data['user']['time'] = '2011-03-07 00:33:45';
how can we add 1 year to this date ?
something like $newdata = $data['user']['time'] + 1 year ?
or
$newdata = 2012-03-07 00:33:45
Thanks
Adam Ramadhan
strtotime() is the function you're looking for:
$data['user']['seal_data'] = date('Y-m-d H:i:s', strtotime('+1 year', strtotime($data['user']['time'])));
First, you have to convert the MySQL datetime to something that PHP can understand. There are two ways of doing this...
Use UNIX_TIMESTAMP() in your query to tell MySQL to return a UNIX timestamp of the datetime column.
SELECT whatever, UNIX_TIMESTAMP(myTime) AS 'myUnixTime' FROM myTable;
Use DateTime::createFromFormat to convert your string time to something PHP can understand.
$date = DateTime::createFromFormat('Y-m-d H:i:s', $data['user']['time']);
Once that is done, you can work with the time... Depending on the method you used above, you can use one of the following.
If you have a unix timestamp, you can use the following to add a year:
$inAYear = strtotime('+1 year', $data['user']['unixTime']);
If you have a DateTime object, you can use the following:
$inAYear = $date->add(new DateInterval('P1Y'));
Now, to display your date in a format that is respectable, you must tell PHP to return a string in the proper format.
If you have a unix timestamp, you can use the following:
$strTime = date('Y-m-d H:i:s', $inAYear);
If you have a DateTime object, you can use the following:
$strTime = $inAYear->format('Y-m-d H:i:s');
Alternatively, if you don't want to deal with all of that, you can simply add one year when you query.
SELECT whatever, DATE_ADD(myTime, INTERVAL 1 YEAR) AS 'inAYear' FROM myTable;
Current (2017) Practice is to use DateTime
This question is top on a google search for "php datetime add one year", but severely outdated. While most of the previous answers will work fine for most cases, the established standard is to use DateTime objects for this instead, primarily due strtotime requiring careful manipulation of timezones and DST.
TL;DR
Convert to DateTime: $date = new DateTime('2011-03-07 00:33:45', [user TZ]);
Use DateTime::modify: $date->modify('+1 year');
Format to needs.
Change the timezone with DateTime::setTimezone from the list of supported timezones: $date->setTimezone(new DateTimeZone('Pacific/Chatham'));
Convert to string with DateTime::format: echo $date->format('Y-m-d H:i:s');
Following this pattern for manipulating dates and times will handle the worst oddities of timezone/DST/leap-time for you.
Just remember two final notes:
Life is easier with your system timezone set at UTC.
NEVER modify the system timezone outside of configuration files.
I've seen too much code that relies on date_default_timezone_set. If you're doing this, stop. Save the timezone in a variable, and pass it around your application instead, please.
More Reading
How to calculate the difference between two dates using PHP?
Convert date format yyyy-mm-dd => dd-mm-yyyy
PHP - strtotime, specify timezone
I think you could use strtotime() to do this pretty easily. Something like:
$newdata = date('c', strtotime($data['user']['time'] . ' +1 year'));
Though the 'c' format string isn't the same as your input format. You could consult date()'s docs for how to construct the correct one.
'Y-m-d H:i:s' — as Tim Cooper suggests — looks correct.
This should do the trick (not tested).
$data = "2011-03-07 00:33:45";
echo 'Original date +1 year: ' . date('Y-m-d H:i:s', strtotime(date("Y-m-d H:i:s", strtotime($data)) . " +1 year"));
First-of-all if your date format is separated by a slash (/), like '2019/12/31' then you should convert it in dash (-) format, like '2019-12-31', to do so use str_replace() function.
$string = str_replace('/', '-', '2019/12/31'); //output: 2019-12-31
To add time/day/month/year do not use strtotime() function, because it can't add a time which is beyond year 2038.
So here I would prefer to use DateTime() function.
$string = '2000-01-01';
$date = new DateTime($string);
$date->add(new DateInterval('P60Y5M2DT6H3M25S')); //60 Years 5 Months 2 Days 6 Hours 3 Minutes 25 Seconds
echo $date->format('Y-m-d H:i:s'); //output: 2060-06-03 06:03:25

Categories