I am using wordpress as my cms..
i had need to schedule post programmatically every 60 seconds
This is the code i am using
function techento_data_valid_schedule($data) {
if ($data['post_type'] == 'post') {
if ($data['post_status'] == 'publish') {
// If post data is invalid then
$time += 60;
$data['post_status'] = 'future';
$data['post_date'] = date('Y-m-d H:i:s', $time);
$data->edit_date = true;
}
}
return $data;
}
add_filter( 'wp_insert_post_data', 'techento_data_valid_schedule', '99', 2 );
but when i publish the post...
it sets the date to jan 1. 1970 ?
Am unable to find the error in the codes ?
You're not setting your $time value anywhere, so when you get to the line $time += 60, you're getting $time = 0 + 60 which, in unixtime is Jan 1, 1970 at 00:01:00.
To correct this, you need to set your $time variable to whatever you need. If you want it to be the current time, try $time = time(); and then add 60 seconds.
Related
I have a somewhat complicated time equation that had been driving me mental!
What I have so far is:
$current = time(); // UTC time
$user_in = '8:00 am'; // local time
$user_out = '4:00 pm'; // local time
$gmt_off = '11'; // Australia EST (+1 at the moment)
I then have the function that will convert the local time to UTC by subtracting the GMT offset, and output it as g:i a
function utc( $time ) {
$time = ( empty($time) ? null : strtotime($time) );
$gmt = '60 * 60 * 11'; // there is an actual check for it to be 10 or 11 - and in seconds
$out = ( $time - $gmt );
$out = date( 'Y-m-d g:i a', $out );
return $out;
}
What I cannot figure out is how to properly configure the conditions to check if the current time is outside the $user times
$user_in_utc = utc( $user_in );
$user_out_utc = utc( $user_out );
if( $current < $user_in_utc && $current > $user_out_utc ) {
// do something
}
However, the problem I'm running into is that say current time is 6:00pm local time.
How do I check it is now currently less than $user_out when it keeps saying the date is today and not tomorrow?
I intend for these functions to run if the statement being true as a cron task
Just use date_default_timezone_set and strtotime to get your timestamp values, and they will all be in the same timezone and hence directly comparable. Note that your condition should use || (or) rather than && (and) to check if the time is outside user hours.
date_default_timezone_set('Australia/Sydney');
$current = strtotime('now');
$user_in = strtotime('8:00 am');
$user_out = strtotime('4:00 pm');
if( $current < $user_in || $current > $user_out ) {
// do something
}
In my code I pretty much send a token to the database with the
date('Y-m-d H:i:s');
function. But I am checking to see if the timestamp I sent if greater than 60 seconds if so i echo yes and else no. I keep getting no and I know its more than a minute because i time it. I've seen post about this but they're using specific dates and I am just going on when a user submits a form and checking if the token is 60 seconds old. Here is my code
php
<?php
require_once('db_login.php');
$stmtToken = $handler->prepare("SELECT * FROM email_token");
$stmtToken->execute();
$rowToken = $stmtToken->fetch();
$date = $rowToken['time_stamp'];
if($date > time() + 60) {
echo 'yes';
} else {
echo 'no';
}
?>
You can also play with dates in different manners. All four lines here are equivalent:
$now = (new \DateTime(date('Y-m-d H:i:s')))->getTimestamp();
$now = (new \DateTime('now'))->getTimestamp();
$now = (new \DateTime())->getTimestamp();
$now = time();
And then you can compare in this manner:
$tokenExpirationTimestamp = (new \DateTime($date))
->modify('+60 seconds')
->getTimestamp();
$isTokenExpired = $tokenExpirationTimestamp < time();
if ($isTokenExpired) {
// ...
}
When you compare times and dates you can either use datetime or strtotime.
Using strings will not work as expected in all cases.
In comments you mentioned how you want to compare, and you need to add the 60 seconds to the "date", not the time().
if(strtotime($date) + 60 < time()) {
I'm scraping a page for articles which all contains of a date in the following format:
2012-08-20T11:04:00+0200
What I want to do is to stop retrieve articles if the next article is posted 12 months from todays date. The way I can think of is the following:
while ($retrieveArticles == true) {
$stopDate = date('Y-m-d'); // <--- this gives me todays date while I need the date 12 months ago.
$date = $article->find('header div p span', 1);
$date = substr($date->title, 0, 10); // <--- becomes 2012-08-20
if ($date >= $stopDate) {
$retrieveArticles = false;
}
... not relevant code
}
What I need help with:
How can I subtract 12 months from todays date?
Am I thinking right by doing like this or is there better and more elegant ways of achieve what I want?
Thanks in advance!
it will be wrong if you compare Y-m-d format of date with together :
you need to convert that to time format with strtotime() function .
for 12 month that is ( 365*24*3600 sec) . so you can change your function like this :
while ($retrieveArticles == true) {
$stopDate = date('Y-m-d'); // <--- this gives me todays date while I need the date 12 months ago.
$date = $article->find('header div p span', 1);
$date = substr($date->title, 0, 10); // <--- becomes 2012-08-20
$stopDate = strtotime($stopDate);
$date = (int)strtotime($date) + (365*24*3600);
if ($stopDate >= $date) {
$retrieveArticles = false;
}
}
Yes, for sure :
$in_12_months = strtotime('+12 months');
while ($retrieveArticles == true) {
$article_date = strtotime($article->find('header div p span', 1));
if ($article_date >= $in_12_months) {
$retrieveArticles = false;
}
}
Here's how I did it:
<?php
$s = strtotime('2012-02-09T11:04:00+0200');
$timeDifference = time() - $s;
echo round($timeDifference / 60 / 60 / 24 / 30);
?>
Output:
11
Convert 2012-08-20T11:04:00+0200 to a timestamp: How to convert date to timestamp in PHP?
and then just do $seconds = time()-$theresult this will be the number of seconds since then. 12 months should be roughly equals to 31 Million Seconds
You could do something like this:
<?php
// Current date
$posted = strtotime("2012-08-20T11:04:00+0200");
// 12 months ago
$timestamp = strtotime("-12 months", $posted);
// days
$days = ($posted - $timestamp) / 60 / 60 / 24;
$get_items = true;
if($days >= 365){
$get_items = false;
}
I am trying to calculate time passed since a comment is posted. I found a function for this and it's working well
But I just noticed the time shown to user is wrong because of his/her timezone. I did some research and the solution seems to be passing the user's timezone offset to the php page using a javascript function called getTimezoneOffset.
the problem is that I can't manage to use this Offset to make a timezone and use it on that function I linked above. With the help of another code is what I could gather so far :
function humanTiming ($time,$offset)
{
$isDST = 1; // Daylight Saving 1 - on, 0 - off
$timezoneName = timezone_name_from_abbr('', intval($offset, 10) * 36, $isDST);
$date = new DateTime($time, new DateTimeZone($timezoneName));
$time = strtotime($date);
$time = time() - $time; // to get the time since that moment
$tokens = array (
31536000 => 'year',
2592000 => 'month',
604800 => 'week',
86400 => 'day',
3600 => 'hour',
60 => 'minute',
1 => 'second'
);
foreach ($tokens as $unit => $text) {
if ($time < $unit) continue;
$numberOfUnits = floor($time / $unit);
return $numberOfUnits.' '.$text.(($numberOfUnits>1)?'s':'');
}
}
And let's call the function like this :
echo humanTiming ($row['date'],"-240");
note : -240 is the value I get from running that javascript function, So it is probably my timezone offset.
First issue: It seems the value -240is invalid and something like -0500 works.
Second issue: even If I try with the valid offset value, the function returns 42 years
Not sure how this 42 years is calculated but its totally wrong.
A couple of problems:
The Javascript function getTimezoneOffset() returns the timezone offset in minutes, however timezone_name_from_abbr() expects the offset in seconds. So in your example of -240 that is actually -4 hours or -14396 seconds. You can fix your code by changing the math a little:
$timezoneName = timezone_name_from_abbr('', intval($offset) * 60, $isDST);
Since you've started using the DateTime object, you can't then use strtotime to get the Unix timestamp. Instead you need format():
$date = new DateTime($time, new DateTimeZone($timezoneName));
$time = $date->format('U');
This should get the result you are after. You were getting 42 years because the time was set to 0 (strtotime($date) evaluated to false) which is Unix epoch - 1970.
You could offset everything like so:
$today=new DateTime("-$offset minutes");
$tomorrow=new DateTime("+1 day-$offset minutes");
I need to check in PHP if the current time is before 2pm that day.
I've done this with strtotime on dates before, however this time it's with a time only, so obviously at 0.00 each day the time will reset, and the boolean will reset from false to true.
if (current_time < 2pm) {
// do this
}
if (date('H') < 14) {
$pre2pm = true;
}
For more information about the date function please see the PHP manual. I have used the following time formatter:
H = 24-hour format of an hour (00 to 23)
Try:
if(date("Hi") < "1400") {
}
See: http://php.net/manual/en/function.date.php
H 24-hour format of an hour with leading zeros 00 through 23
i Minutes with leading zeros 00 to 59
You could just pass in the time
if (time() < strtotime('2 pm')) {
//not yet 2 pm
}
Or pass in the date explicitly as well
if (time() < strtotime('2 pm ' . date('d-m-Y'))) {
//not yet 2 pm
}
Use 24 hour time to get round the problem like so:
$time = 1400;
$current_time = (int) date('Hi');
if($current_time < $time) {
// do stuff
}
So 2PM equates to 14:00 in 24 hour time. If we remove the colon from the time then we can evaluate it as an integer in our comparison.
For more information about the date function please see the PHP manual. I have used the following time formatters:
H = 24-hour format of an hour (00 to 23)
i = Minutes with leading zeros (00 to 59)
You haven't told us which version of PHP you're running, although, assuming it's PHP 5.2.2+ than you should be able do it like:
$now = new DateTime();
$twoPm = new DateTime();
$twoPm->setTime(14,0); // 2:00 PM
then just ask:
if ( $now < $twoPm ){ // such comparison exists in PHP >= 5.2.2
// do this
}
otherwise, if you're using one of older version (say, 5.0) this should do the trick (and is much simplier):
$now = time();
$twoPm = mktime(14); // first argument is HOUR
if ( $now < $twoPm ){
// do this
}
If you want to check whether the time is before 2.30 pm ,you can try the following code segment .
if (date('H') < 14.30) {
$pre2pm = true;
}else{
$pre2pm = false;
}
Try with
if( time() < mktime(14, 0, 0, date("n"), date("j"), date("Y")) ) {
// do this
}
This function will check if it's between hours in EST by accepting 2 params, arrays with the hour and am/pm...
/**
* Check if between hours array(12,'pm'), array(2,'pm')
*/
function is_between_hours($h1 = array(), $h2 = array())
{
date_default_timezone_set('US/Eastern');
$est_hour = date('H');
$h1 = ($h1[1] == 'am') ? $h1[0] : $h1[0]+12;
$h1 = ($h1 === 24) ? 12 : $h1;
$h2 = ($h2[1] == 'am') ? $h2[0] : $h2[0]+12;
$h2 = ($h2 === 24) ? 12 : $h2;
if ( $est_hour >= $h1 && $est_hour <= ($h2-1) )
return true;
return false;
}
Use time(), date() and strtotime() functions:
if(time() > strtotime(date('Y-m-d').' 14:00') {
//...
}