Last active
June 1, 2018 20:11
-
-
Save DaveyJake/d74357a3b68a8bfad6f41e393f8caa5c to your computer and use it in GitHub Desktop.
Better WP Time Constants
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/** | |
* Constants for the exact number of seconds in any given year and in any given | |
* month on the Gregorian calendar. Meant to be used in place of the current | |
* 'YEAR_IN_SECONDS' and 'MONTH_IN_SECONDS' integrations found in | |
* {@link https://codex.wordpress.org/Easier_Expression_of_Time_Constants|WordPress}. | |
* | |
* @author Davey Jacobson <djacobson@usarugby.org> | |
* @package DJ_Exact_Year_Month_Time_Constants | |
*/ | |
if ( ! defined( 'ABSPATH' ) ) exit; | |
class DJ_Exact_Year_Month_Time_Constants { | |
function __construct() { | |
add_action( 'init', array( $this, 'constants' ), 1 ); | |
} | |
/** | |
* Custom Date/Time Constants | |
* | |
* @since 1.0.0 | |
*/ | |
private function constants() { | |
if ( ! defined( 'YEAR_IN_SECS' ) ) { | |
define( 'YEAR_IN_SECS', $this->year_in_seconds() ); | |
} | |
if ( ! defined( 'MONTH_IN_SECS' ) ) { | |
define( 'MONTH_IN_SECS', $this->month_in_seconds() ); | |
} | |
} | |
/** | |
* Calculate number of seconds for each month. | |
* | |
* @return int This month in seconds. | |
*/ | |
public function month_in_seconds() { | |
static $month_in_seconds = null; | |
$key = date( 'M' ); | |
$days_per_month = array( | |
'Jan' => 31, | |
'Feb' => ( $this->is_leap_year() ? 29 : 28 ), | |
'Mar' => 31, | |
'Apr' => 30, | |
'May' => 31, | |
'Jun' => 30, | |
'Jul' => 31, | |
'Aug' => 31, | |
'Sep' => 30, | |
'Oct' => 31, | |
'Nov' => 30, | |
'Dev' => 31, | |
); | |
if ( isset( $days_per_month[ $key ] ) ) { | |
$month_in_seconds = ( $days_per_month[ $key ] * DAY_IN_SECONDS ); | |
} | |
return $month_in_seconds; | |
} | |
/** | |
* Account for WP default constants lack of depth. | |
* | |
* @return int This year in seconds. | |
*/ | |
public function year_in_seconds() { | |
static $year_in_seconds = null; | |
if ( $this->is_leap_year() ) { | |
$year_in_seconds = ( YEAR_IN_SECONDS + DAY_IN_SECONDS ); | |
} | |
else { | |
$year_in_seconds = YEAR_IN_SECONDS; | |
} | |
return $year_in_seconds; | |
} | |
/** | |
* Check if it's currently a 'leap year'. | |
* | |
* @return bool | |
*/ | |
public function is_leap_year() { | |
// Ensure that '0' isn't read as boolean. | |
$zero = (int) 0; | |
// Current Year | |
$year = date( 'Y' ); | |
// No remainders means it's a leap year! | |
return ( $year % 4 === $zero ) ? true : false; | |
} | |
} | |
new DJ_Exact_Year_Month_Time_Constants(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment