Files
verta/src/Verta.php
T
2017-06-04 19:10:37 +04:30

1793 lines
42 KiB
PHP
Executable File
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
<?php
namespace Hekmatinasser\Verta;
/*
* This file is part of the Jalali package.
*
* (c) Nasser Hekmati <hekmati.nasser@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
use DateTime;
use DateTimeZone;
use DatePeriod;
use InvalidArgumentException;
use Exception;
class Verta extends DateTime {
/***************************** STATCT VARIABLE ****************************/
/**
* The day constants
*/
const SATURDAY = 0;
const SUNDAY = 1;
const MONDAY = 2;
const TUESDAY = 3;
const WEDNESDAY = 4;
const THURSDAY = 5;
const FRIDAY = 6;
/**
* Number unit in date
*/
const YEARS_PER_CENTURY = 100;
const YEARS_PER_DECADE = 10;
const MONTHS_PER_YEAR = 12;
const WEEKS_PER_YEAR = 52;
const WEEKS_PER_MONTH = 4.35;
const DAYS_PER_WEEK = 7;
const HOURS_PER_DAY = 24;
const MINUTES_PER_HOUR = 60;
const SECONDS_PER_MINUTE = 60;
/**
* Word use in format datetime.
*/
const DEFAULT_STRING_FORMAT = 'Y-m-d H:i:s';
/**
* Format to use for __toString.
*
* @var string
*/
protected static $stringFormat = self::DEFAULT_STRING_FORMAT;
/**
* @var array
*/
protected static $formats = array(
'datetime' => 'Y-m-d H:i:s',
'date' => 'Y-m-d',
'time' => 'H:i:s',
);
/**
* Default format to use for __toString method when type juggling occurs.
*/
const AM = 'ق.ظ';
const PM = 'ب.ظ';
const ANTE_MERIDIEM = 'قبل از ظهر';
const POST_MERIDIEM = 'بعد از ظهر';
const NUMBER_TH = ' ام';
const PRE = 'پیش';
const POST = 'بعد';
/**
* number day in months gregorian
*
* @var array
*/
protected static $daysMonthGregorian = array(
31,
28,
31,
30,
31,
30,
31,
31,
30,
31,
30,
31,
);
/**
* number day in month jalali
*
* @var array
*/
protected static $daysMonthJalali = array(
31,
31,
31,
31,
31,
31,
30,
30,
30,
30,
30,
29,
);
/**
* month name jalali
*
* @var array
*/
protected static $monthYear = array(
'فرودین',
'اردیبهشت',
'خرداد',
'تیر',
'مرداد',
'شهریور',
'مهر',
'آبان',
'آذر',
'دی',
'بهمن',
'اسفند',
);
/**
* Names of days of the week.
*
* @var array
*/
protected static $dayWeek = array(
'شنبه',
'یکشنبه',
'دوشنبه',
'سه شنبه',
'چهارشنبه',
'پنج شنبه',
'جمعه',
);
/**
* unit date name.
*
* @var array
*/
protected static $unitName = array(
'ثانیه',
'دقیقه',
'ساعت',
'روز',
'هفته',
'ماه',
'سال',
'قرن'
);
/**
* unit date number.
*
* @var array
*/
protected static $unitNumber = array(
self::SECONDS_PER_MINUTE,
self::MINUTES_PER_HOUR,
self::HOURS_PER_DAY,
self::DAYS_PER_WEEK,
self::WEEKS_PER_MONTH,
self::MONTHS_PER_YEAR,
self::YEARS_PER_DECADE,
);
/**
* persian number.
*
* @var array
*/
protected static $persianNumber = array(
'۰',
'۱',
'۲',
'۳',
'۴',
'۵',
'۶',
'۷',
'۸',
'۹',
);
/**
* english number.
*
* @var array
*/
protected static $englishNumber = array(
'0',
'1',
'2',
'3',
'4',
'5',
'6',
'7',
'8',
'9',
);
/***************************** CONSTRUCT ****************************/
/**
* create object of Jalali
*
* @param timestamp $timestamp [optional]
* @param bool $timezone [optional]
*/
public function __construct($datetime = null, $timezone = null) {
date_default_timezone_set('Asia/Tehran');
if ($datetime === null) {
$instance = time();
}
elseif (is_string($datetime)){
$object = date_create($datetime);
if ($object === false) {
throw new InvalidArgumentException(sprintf("Unknown datetime '%s'", $datetime));
}
$instance = $object->getTimestamp();
}
elseif ($datetime instanceof DateTime || $datetime instanceof Verta) {
$instance = $datetime->getTimestamp();
}
elseif (is_numeric($datetime)) {
$instance = $datetime;
}
else {
throw new \InvalidArgumentException(sprintf("Unknown datetime '%s'", $datetime));
}
$timezone = static::createTimeZone($timezone);
parent::__construct(date('Y-m-d H:i:s.u', $instance), $timezone);
}
/**
* Create a Verta now datetime
*
*
* @return static
*/
public static function now() {
return new static();
}
/**
* Create a Verta instance for today.
*
* @param \DateTimeZone|string|null $timezone
*
* @return static
*/
public static function today($timezone = null)
{
return static::now($timezone)->startOfDay();
}
/**
* Create a Verta instance for tomorrow.
*
* @param \DateTimeZone|string|null $timezone
*
* @return static
*/
public static function tomorrow($timezone = null)
{
return static::today($timezone)->addDay();
}
/**
* Create a Verta instance for yesterday.
*
* @param \DateTimeZone|string|null $timezone
*
* @return static
*/
public static function yesterday($timezone = null)
{
return static::today($timezone)->subDay();
}
/**
* Create a Verta instance from a DateTime one
*
* @param timestamp $datetime [optional]
* @param bool $timezone [optional]
*
* @return static
*/
public static function instance($datetime = null, $timezone = null) {
return new static($datetime, $timezone);
}
/**
* Create a DateTime instance from Verta
*
* @return DateTime $datetime
*/
public function DateTime() {
return new DateTime(date('Y-m-d H:i:s.u', $this->getTimestamp()), $this->getTimeZone());
}
/**
* Create a Verta instance from a DateTime one
*
* @param timestamp $datetime [optional]
* @param bool $timezone [optional]
*
* @return static
*/
public static function parse($datetime, $timezone = null) {
$parse = date_parse($datetime);
if($parse['error_count'] == 0){
list($year, $month, $day) = self::getGregorian($parse['year'], $parse['month'], $parse['day']);
list( $hour,$minute, $second) = array($parse['hour'], $parse['minute'], $parse['second']);
$timezone = self::createTimeZone($timezone);
$datetime = new DateTime(sprintf('%04s-%02s-%02s %02s:%02s:%02s', $year, $month, $day, $hour, $minute, $second), $timezone);
return new static($datetime);
}
else{
throw new InvalidArgumentException(sprintf("Unknown datetime '%s'", $datetime));
}
}
/**
* Create a new Verta instance from a specific date and time gregorain.
*
* If any of feild are set to null their now() values will
* be used.
*
* @param int|null $year
* @param int|null $month
* @param int|null $day
* @param int|null $hour
* @param int|null $minute
* @param int|null $second
* @param \DateTimeZone|string|null $timezone
*
* @return static
*/
public static function create($year = null, $month = null, $day = null, $hour = null, $minute = null, $second = null, $timezone = null)
{
return static::createGregorian($year, $month, $day, $hour, $minute, $second, $timezone);
}
/**
* Create a Verta from just a date gregorian.
*
* @param int|null $year
* @param int|null $month
* @param int|null $day
* @param \DateTimeZone|string|null $timezone
*
* @return static
*/
public static function createDate($year = null, $month = null, $day = null, $timezone = null)
{
return static::create($year, $month, $day, null, null, null, $timezone);
}
/**
* Create a Verta instance from just a time gregorian.
*
* @param int|null $hour
* @param int|null $minute
* @param int|null $second
* @param \DateTimeZone|string|null $timezone
*
* @return static
*/
public static function createTime($hour = null, $minute = null, $second = null, $timezone = null)
{
return static::create(null, null, null, $hour, $minute, $second, $timezone);
}
/**
* Create a Verta instance from a timestamp.
*
* @param int $timestamp
* @param \DateTimeZone|string|null $timezone
*
* @return static
*/
public static function createTimestamp($timestamp, $timezone = null)
{
return static::instance($timestamp, $timezone);
}
/**
* @param null $timezone
* @return DateTimeZone|null
*/
protected static function createTimeZone($timezone = null) {
if ($timezone === null) {
return new DateTimeZone('Asia/Tehran');
}
if ($timezone instanceof DateTimeZone) {
return $timezone;
}
$object = @timezone_open(strval($timezone));
if ($object === false) {
throw new InvalidArgumentException(sprintf("Unknown timezone '%s'", $timezone));
}
return $object;
}
/**
* Create a new Verta instance from a specific date and time gregorain.
*
* If any of feild are set to null their now() values will
* be used.
*
* @param int|null $year
* @param int|null $month
* @param int|null $day
* @param int|null $hour
* @param int|null $minute
* @param int|null $second
* @param \DateTimeZone|string|null $timezone
*
* @return static
*/
public static function createGregorian($year = null, $month = null, $day = null, $hour = null, $minute = null, $second = null, $timezone = null)
{
$now = date('Y-n-j-G-i-s', time());
$defaults = array_combine(array('year', 'month', 'day', 'hour', 'minute', 'second'), explode('-', $now));
$year = $year === null ? intval($defaults['year']) : $year;
$month = $month === null ? intval($defaults['month']) : $month;
$day = $day === null ? intval($defaults['day']) : $day;
$hour = $hour === null ? intval($defaults['hour']) : $hour;
$minute = $minute === null ? intval($defaults['minute']) : $minute;
$second = $second === null ? intval($defaults['second']) : $second;
if (!checkdate($year, $month, $day) || !static::isValideTime($hour, $minute, $second)) {
throw new \InvalidArgumentException('Unknown datetime');
}
return static::instance(sprintf('%s-%s-%s %s:%s:%s', $year, $month, $day, $hour, $minute, $second), $timezone);
}
/**
* Create a Verta from just a date gregorian.
*
* @param int|null $year
* @param int|null $month
* @param int|null $day
* @param \DateTimeZone|string|null $timezone
*
* @return static
*/
public static function createGregorianDate($year = null, $month = null, $day = null, $timezone = null)
{
return static::createGregorian($year, $month, $day, null, null, null, $timezone);
}
/**
* Create a Verta instance from just a time gregorian.
*
* @param int|null $hour
* @param int|null $minute
* @param int|null $second
* @param \DateTimeZone|string|null $timezone
*
* @return static
*/
public static function createGregorianTime($hour = null, $minute = null, $second = null, $timezone = null)
{
return static::createGregorian(null, null, null, $hour, $minute, $second, $timezone);
}
/**
* Create a new Verta instance from a specific date and time.
*
* If any of feild are set to null their now() values will
* be used.
*
* @param int|null $year
* @param int|null $month
* @param int|null $day
* @param int|null $hour
* @param int|null $minute
* @param int|null $second
* @param \DateTimeZone|string|null $timezone
*
* @return static
*/
public static function createJalali($year = null, $month = null, $day = null, $hour = null, $minute = null, $second = null, $timezone = null)
{
$now = static::instance(null, $timezone)->format('Y-n-j-G-i-s');
$defaults = array_combine(array('year', 'month', 'day', 'hour', 'minute', 'second'), explode('-', $now));
$year = $year === null ? intval($defaults['year']) : $year;
$month = $month === null ? intval($defaults['month']) : $month;
$day = $day === null ? intval($defaults['day']) : $day;
$hour = $hour === null ? intval($defaults['hour']) : $hour;
$minute = $minute === null ? intval($defaults['minute']) : $minute;
$second = $second === null ? intval($defaults['second']) : $second;
if (!static::isValideDate($year, $month, $day) || !static::isValideTime($hour, $minute, $second)) {
throw new \InvalidArgumentException('Unknown datetime');
}
return static::parse(sprintf('%s-%s-%s %s:%s:%s', $year, $month, $day, $hour, $minute, $second));
}
/**
* Create a Verta from just a date.
*
* @param int|null $year
* @param int|null $month
* @param int|null $day
* @param \DateTimeZone|string|null $timezone
*
* @return static
*/
public static function createJalaliDate($year = null, $month = null, $day = null, $timezone = null)
{
return static::createJalali($year, $month, $day, null, null, null, $timezone);
}
/**
* Create a Verta instance from just a time.
*
* @param int|null $hour
* @param int|null $minute
* @param int|null $second
* @param \DateTimeZone|string|null $timezone
*
* @return static
*/
public static function createJalaliTime($hour = null, $minute = null, $second = null, $timezone = null)
{
return static::createJalali(null, null, null, $hour, $minute, $second, $timezone);
}
/***************************** ACCESS ****************************/
/**
* Get a part of the Verta object
*
* @param string $name
*
* @throws \InvalidArgumentException
*
* @return string|int|\DateTimeZone
*/
public function __get($name)
{
switch (true) {
case array_key_exists($name, $formats = array(
'year' => 'Y',
'month' => 'n',
'day' => 'j',
'hour' => 'G',
'minute' => 'i',
'second' => 's',
'micro' => 'u',
'dayOfWeek' => 'w',
'dayOfYear' => 'z',
'weekOfYear' => 'W',
'daysInMonth' => 't',
'timestamp' => 'U',
)):
return (int) $this->format($formats[$name]);
case $name === 'timezone':
return $this->getTimezone()->getName();
default:
throw new InvalidArgumentException(sprintf("Unknown getter '%s'", $name));
}
}
/**
* Check if an attribute exists on the object
*
* @param string $name
*
* @return bool
*/
public function __isset($name)
{
try {
$this->__get($name);
} catch (InvalidArgumentException $e) {
return false;
}
return true;
}
/**
* Set a part of the Verta object
*
* @param string $name
* @param string|int|\DateTimeZone $value
*
* @throws \InvalidArgumentException
*/
public function __set($name, $value)
{
switch ($name) {
case 'year':
case 'month':
case 'day':
case 'hour':
case 'minute':
case 'second':
list($year, $month, $day, $hour, $minute, $second) = explode('-', $this->format('Y-n-j-G-i-s'));
$$name = $value;
$this->setDateTime($year, $month, $day, $hour, $minute, $second);
break;
case 'timestamp':
$this->setTimestamp($value);
break;
case 'timezone':
case 'tz':
$this->setTimezone(new DateTimeZone($value));
break;
default:
throw new InvalidArgumentException(sprintf("Unknown setter '%s'", $name));
}
}
/**
* Set the instance's year
*
* @param int $value
*
* @return static
*/
public function year($value)
{
$this->year = $value;
return $this;
}
/**
* Set the instance's month
*
* @param int $value
*
* @return static
*/
public function month($value)
{
$this->month = $value;
return $this;
}
/**
* Set the instance's day
*
* @param int $value
*
* @return static
*/
public function day($value)
{
$this->day = $value;
return $this;
}
/**
* Set the instance's hour
*
* @param int $value
*
* @return static
*/
public function hour($value)
{
$this->hour = $value;
return $this;
}
/**
* Set the instance's minute
*
* @param int $value
*
* @return static
*/
public function minute($value)
{
$this->minute = $value;
return $this;
}
/**
* Set the instance's second
*
* @param int $value
*
* @return static
*/
public function second($value)
{
$this->second = $value;
return $this;
}
/**
* Set the instance's timestamp
*
* @param int $value
*
* @return static
*/
public function timestamp($value)
{
return parent::setTimestamp($value);
}
/**
* Alias for setTimezone()
*
* @param \DateTimeZone|string $value
*
* @return static
*/
public function timezone($value)
{
return parent::setTimezone(new DateTimeZone($value));
}
/**
* Set the date and time all together
*
* @param int $year
* @param int $month
* @param int $day
* @param int $hour
* @param int $minute
* @param int $second
*
* @return static
*/
public function setDateTime($year, $month, $day, $hour, $minute, $second = 0, $microseconds = 0)
{
return $this->setDate($year, $month, $day)->setTime($hour, $minute, $second, $microseconds);
}
/**
* Sets the current date of the DateTime object to a different date.
* Calls modify as a workaround for a php bug
*
* @param int $year
* @param int $month
* @param int $day
*
* @return static
*/
public function setDate($year, $month, $day)
{
list($year, $month, $day) = self::getGregorian($year, $month, $day);
return parent::setDate($year, $month, $day);
}
/**
* Set the time by time string
*
* @param string $time
*
* @return static
*
* @throws \InvalidArgumentException
*/
public function setTimeString($time)
{
$time = explode(':', $time);
$hour = $time[0];
$minute = isset($time[1]) ? $time[1] : 0;
$second = isset($time[2]) ? $time[2] : 0;
return $this->setTime($hour, $minute, $second, 0);
}
/***************************** STRING FORMATED ****************************/
/**
* Reset the format used to the default when type juggling a Carbon instance to a string
*/
public static function resetStringFormat()
{
static::setStringFormat(static::DEFAULT_STRING_FORMAT);
}
/**
* Set the default format used when type juggling a Carbon instance to a string
*
* @param string $format
*/
public static function setStringFormat($format)
{
static::$stringFormat = $format;
}
/**
* Format the instance as a string using the set format
*
* @return string
*/
public function __toString()
{
return $this->format(static::$stringFormat);
}
/**
* The format of the outputted date string (jalali equivalent of php date() function)
*
* @param string $format for example 'Y-m-d H:i:s'
* @return string
*/
protected function date($format){
$timestamp = $this->getTimestamp();
list($gYear, $gMonth, $gDay, $gWeek) = explode('-', date('Y-m-d-w', $timestamp));
list($pYear, $pMonth, $pDay) = static::getJalali($gYear, $gMonth, $gDay);
$pWeek = ($gWeek + 1);
if ($pWeek >= 7) {
$pWeek = 0;
}
if ($format == '\\') {
$format = '//';
}
$lenghFormat = strlen($format);
$i = 0;
$result = '';
while ($i < $lenghFormat) {
$par = $format{$i};
if ($par == '\\') {
$result .= $format{ ++$i};
$i ++;
continue;
}
switch ($par) {
# Day
case 'd':
$result .= sprintf('%02s', $pDay);
break;
case 'D':
$result .= substr(static::$dayWeek[$pWeek], 0, 2);
break;
case 'j':
$result .= $pDay;
break;
case 'l':
$result .= static::$dayWeek[$pWeek];
break;
case 'N':
$result .= $pWeek + 1;
break;
case 'w':
$result .= $pWeek;
break;
case 'z':
$result .= $this->daysYear($pMonth, $pDay);
break;
case 'S':
$result .= self::NUMBER_TH;
break;
# Week
case 'W':
$result .= ceil($this->daysYear($pMonth, $pDay) / 7);
break;
# Month
case 'F':
$result .= static::$monthYear[$pMonth-1];
break;
case 'm':
$result .= sprintf('%02s', $pMonth);
break;
case 'M':
$result .= substr(static::$monthYear[$pMonth-1], 0, 6);
break;
case 'n':
$result .= $pMonth;
break;
case 't':
$result .= $this->daysMonthJalali($pYear,$pMonth);
break;
# Years
case 'L':
$result .= intval($this->isLeapYear($pYear));
break;
case 'Y':
case 'o':
$result .= $pYear;
break;
case 'y':
$result .= substr($pYear, 2);
break;
# Time
case 'a':
case 'A':
if (date('a', $timestamp) == 'am') {
$result .= (($par == 'a') ? self::AM : self::ANTE_MERIDIEM);
} else {
$result .= (($par == 'a') ? self::PM : self::POST_MERIDIEM);
}
break;
case 'B':
case 'g':
case 'G':
case 'h':
case 'H':
case 's':
case 'u':
case 'i':
# Timezone
case 'e':
case 'I':
case 'O':
case 'P':
case 'T':
case 'Z':
$result .= date($par, $timestamp);
break;
# Full Date/Time
case 'c':
$result .= ($pYear . '-' . $pMonth . '-' . $pDay . ' ' . date('H:i:s P', $timestamp));
break;
case 'r':
$result .= (substr(static::$dayWeek[$pWeek], 0, 2) . '، ' . $pDay . ' ' . substr(static::$monthYear[$pMonth], 0, 6) . ' ' . $pYear . ' ' . date('H:i:s P', $timestamp));
break;
case 'U':
$result .= $timestamp;
break;
default:
$result .= $par;
}
$i ++;
}
return $result;
}
/**
* The format of the outputted date string (jalali equivalent of php strftime() function)
*
* @param $format
* @return string
*/
protected function strftime($format)
{
$str_format_code = array(
"%a",
"%A",
"%d",
"%e",
"%j",
"%u",
"%w",
"%U",
"%V",
"%W",
"%b",
"%B",
"%h",
"%m",
"%C",
"%g",
"%G",
"%y",
"%Y",
"%H",
"%I",
"%l",
"%M",
"%p",
"%P",
"%r",
"%R",
"%S",
"%T",
"%X",
"%z",
"%Z",
"%c",
"%D",
"%F",
"%s",
"%x",
"%n",
"%t",
"%%",
);
$date_format_code = array(
"D",
"l",
"d",
"j",
"z",
"N",
"w",
"W",
"W",
"W",
"M",
"F",
"M",
"m",
"y",
"y",
"y",
"y",
"Y",
"H",
"h",
"g",
"i",
"A",
"a",
"h:i:s A",
"H:i",
"s",
"H:i:s",
"h:i:s",
"H",
"H",
"D j M H:i:s",
"d/m/y",
"Y-m-d",
"U",
"d/m/y",
"\n",
"\t",
"%",
);
//Change Strftime format to Date format
$format = str_replace($str_format_code, $date_format_code, $format);
//Convert to date
return $this->date($format);
}
/**
* The format of the outputted date string (jalali equivalent of php strftime() function)
*
* @param $format
* @return string
*/
public function format($format) {
if (in_array($format, array_keys(self::$formats))) {
$format = self::$formats[$format];
}
return $this->strftime($format);
}
/**
* The format of the outputted date string (gregorian)
*
* @param $format
* @return string
*/
public function formatGregorian($format) {
return $this->DateTime()->format($format);
}
/**
* Format the instance as date
*
* @return string
*/
public function formatDatetime()
{
return $this->format('Y-m-d H:i:s');
}
/**
* Format the instance as date
*
* @return string
*/
public function formatDate()
{
return $this->format('Y-m-d');
}
/**
* Format the instance as time
*
* @return string
*/
public function formatTime()
{
return $this->format('H:i:s');
}
/**
* Format the instance as date
*
* @return string
*/
public function formatJalaliDatetime()
{
return $this->format('Y/n/j H:i:s');
}
/**
* Format the instance as date
*
* @return string
*/
public function formatJalaliDate()
{
return $this->format('Y/n/j');
}
/**
* Convert english numbers to persian numbers
*
* @param string $string
* @return string
*/
public static function persianNumbers($string)
{
return str_replace(self::$englishNumber, self::$persianNumber, $string);
}
/***************************** COMPERTION ****************************/
/**
* check jalali the instance is a leap year
*
* @param int $year
* @return bool
*/
public static function isLeapYear($year) {
$mod = ($year % 33);
if (($mod == 1) or ( $mod == 5) or ( $mod == 9) or ( $mod == 13) or ( $mod == 17) or ( $mod == 22) or ( $mod == 26) or ( $mod == 30)) {
return true;
}
return false;
}
/**
* validate a jalali date (jalali equivalent of php checkdate() function)
*
* @param int $month
* @param int $day
* @param int $year
* @return bool
*/
public static function isValideDate($year, $month, $day) {
return $year >= 1 && $year <= 32766
&& $month >= 1 && $month <= 12
&& $day >= 1 && $day <= static::daysMonthJalali($year, $month);
}
/**
* validate a time
*
* @param int $hour
* @param int $minute
* @param int $second
* @return bool
*/
public static function isValideTime($hour, $minute, $second) {
return $hour >= 0 && $hour <= 24
&& $minute >= 0 && $minute <= 59
&& $second >= 0 && $second <= 59;
}
/**
* get difference to now
*
* @return string
*/
public function diffNow()
{
$now = time();
// get difference
$difference = $now - $this->getTimestamp();
$negative = true;
// set descriptor
if ($difference < 0) {
$difference = abs($difference); // absolute value
$negative = false;
}
// do math
for ($j = 0; $difference >= static::$unitNumber[$j] and $j < count(static::$unitNumber) - 1; $j++) {
$difference /= static::$unitNumber[$j];
}
// round difference
$difference = intval(round($difference));
$timebound = ($negative ? self::PRE : self::POST);
return sprintf('%s %s %s', $difference, static::$unitName[$j], $timebound);
}
/***************************** CALCULATION ****************************/
/**
* Add years to the instance. Positive $value travel forward while
* negative $value travel into the past.
*
* @param int $value
*
* @return static
*/
public function addYears($value)
{
return $this->modify((int) $value.' year');
}
/**
* Add a year to the instance
*
* @param int $value
*
* @return static
*/
public function addYear($value = 1)
{
return $this->addYears($value);
}
/**
* Remove years from the instance.
*
* @param int $value
*
* @return static
*/
public function subYears($value)
{
return $this->addYears(-1 * $value)->modify('-1 day');
}
/**
* Remove a year from the instance
*
* @param int $value
*
* @return static
*/
public function subYear($value = 1)
{
return $this->subYears($value);
}
/**
* Add months to the instance. Positive $value travels forward while
* negative $value travels into the past.
*
* @param int $value
*
* @return static
*/
public function addMonths($value)
{
list($year, $month, $day, $hour, $minute, $second) = explode('-', $this->format('Y-m-d-H-i-s'));
$month += $value;
if ($month > 12) {
$year += intval($month / 12);
$month = $month % 12;
}
if ($month < 1) {
$year += intval($month / 12) - 1;
$month = 12 + ($month % 12);
}
if ($value > 0) {
if ($month > 6 && $day == 31) {
$day--;
}
if ($month == 12 && !self::isLeapYear($year)) {
$day--;
}
}
else {
if ($month == 12 && $day == 31) {
if (self::isLeapYear($year)) {
$day = 30;
}
else {
$day = 29;
}
}
}
return self::createJalali($year, $month, $day, $hour, $minute, $second, $this->getTimeZone());
}
/**
* Add a month to the instance
*
* @param int $value
*
* @return static
*/
public function addMonth($value = 1)
{
return $this->addMonths($value);
}
/**
* Remove a month from the instance
*
* @param int $value
*
* @return static
*/
public function subMonth($value = 1)
{
return $this->subMonths($value);
}
/**
* Remove months from the instance
*
* @param int $value
*
* @return static
*/
public function subMonths($value)
{
return $this->addMonths(-1 * $value);
}
/**
* Add days to the instance. Positive $value travels forward while
* negative $value travels into the past.
*
* @param int $value
*
* @return static
*/
public function addDays($value)
{
return $this->modify((int) $value.' day');
}
/**
* Add a day to the instance
*
* @param int $value
*
* @return static
*/
public function addDay($value = 1)
{
return $this->addDays($value);
}
/**
* Remove a day from the instance
*
* @param int $value
*
* @return static
*/
public function subDay($value = 1)
{
return $this->subDays($value);
}
/**
* Remove days from the instance
*
* @param int $value
*
* @return static
*/
public function subDays($value)
{
return $this->addDays(-1 * $value);
}
/**
* Add weeks to the instance. Positive $value travels forward while
* negative $value travels into the past.
*
* @param int $value
*
* @return static
*/
public function addWeeks($value)
{
return $this->modify((int) $value.' week');
}
/**
* Add a week to the instance
*
* @param int $value
*
* @return static
*/
public function addWeek($value = 1)
{
return $this->addWeeks($value);
}
/**
* Remove a week from the instance
*
* @param int $value
*
* @return static
*/
public function subWeek($value = 1)
{
return $this->subWeeks($value);
}
/**
* Remove weeks to the instance
*
* @param int $value
*
* @return static
*/
public function subWeeks($value)
{
return $this->addWeeks(-1 * $value);
}
/**
* Add hours to the instance. Positive $value travels forward while
* negative $value travels into the past.
*
* @param int $value
*
* @return static
*/
public function addHours($value)
{
return $this->modify((int) $value.' hour');
}
/**
* Add an hour to the instance
*
* @param int $value
*
* @return static
*/
public function addHour($value = 1)
{
return $this->addHours($value);
}
/**
* Remove an hour from the instance
*
* @param int $value
*
* @return static
*/
public function subHour($value = 1)
{
return $this->subHours($value);
}
/**
* Remove hours from the instance
*
* @param int $value
*
* @return static
*/
public function subHours($value)
{
return $this->addHours(-1 * $value);
}
/**
* Add minutes to the instance. Positive $value travels forward while
* negative $value travels into the past.
*
* @param int $value
*
* @return static
*/
public function addMinutes($value)
{
return $this->modify((int) $value.' minute');
}
/**
* Add a minute to the instance
*
* @param int $value
*
* @return static
*/
public function addMinute($value = 1)
{
return $this->addMinutes($value);
}
/**
* Remove a minute from the instance
*
* @param int $value
*
* @return static
*/
public function subMinute($value = 1)
{
return $this->subMinutes($value);
}
/**
* Remove minutes from the instance
*
* @param int $value
*
* @return static
*/
public function subMinutes($value)
{
return $this->addMinutes(-1 * $value);
}
/**
* Add seconds to the instance. Positive $value travels forward while
* negative $value travels into the past.
*
* @param int $value
*
* @return static
*/
public function addSeconds($value)
{
return $this->modify((int) $value.' second');
}
/**
* Add a second to the instance
*
* @param int $value
*
* @return static
*/
public function addSecond($value = 1)
{
return $this->addSeconds($value);
}
/**
* Remove a second from the instance
*
* @param int $value
*
* @return static
*/
public function subSecond($value = 1)
{
return $this->subSeconds($value);
}
/**
* Remove seconds from the instance
*
* @param int $value
*
* @return static
*/
public function subSeconds($value)
{
return $this->addSeconds(-1 * $value);
}
/***************************** MODIFY ****************************/
/**
* Resets the time to 00:00:00
*
* @return static
*/
public function startOfDay()
{
return $this->setTime(0, 0, 0);
}
/**
* Resets the time to 23:59:59
*
* @return static
*/
public function endOfDay()
{
return $this->setTime(23, 59, 59);
}
/***************************** TRANSFORMATION ****************************/
/**
* gregorian to jalali convertion
*
* @param int $g_y
* @param int $g_m
* @param int $g_d
* @return array
*/
public static function getJalali($g_y, $g_m, $g_d) {
$gy = $g_y - 1600;
$gm = $g_m - 1;
$g_day_no = (365 * $gy + static::div($gy + 3, 4) - static::div($gy + 99, 100) + static::div($gy + 399, 400));
for ($i = 0; $i < $gm; ++$i) {
$g_day_no += static::$daysMonthGregorian[$i];
}
if ($gm > 1 && (($gy % 4 == 0 && $gy % 100 != 0) || ($gy % 400 == 0)))
# leap and after Feb
$g_day_no ++;
$g_day_no += $g_d - 1;
$j_day_no = $g_day_no - 79;
$j_np = static::div($j_day_no, 12053); # 12053 = (365 * 33 + 32 / 4)
$j_day_no = $j_day_no % 12053;
$jy = (979 + 33 * $j_np + 4 * static::div($j_day_no, 1461)); # 1461 = (365 * 4 + 4 / 4)
$j_day_no %= 1461;
if ($j_day_no >= 366) {
$jy += static::div($j_day_no - 1, 365);
$j_day_no = ($j_day_no - 1) % 365;
}
for ($i = 0; ($i < 11 && $j_day_no >= static::$daysMonthJalali[$i]); ++$i) {
$j_day_no -= static::$daysMonthJalali[$i];
}
return array($jy, $i + 1, $j_day_no + 1);
}
/**
* jalali to gregorian convertion
*
* @param int $j_y
* @param int $j_m
* @param int $j_d
* @return array
*/
public static function getGregorian($j_y, $j_m, $j_d) {
$jy = $j_y - 979;
$jm = $j_m - 1;
$j_day_no = (365 * $jy + static::div($jy, 33) * 8 + static::div($jy % 33 + 3, 4));
for ($i = 0; $i < $jm; ++$i) {
$j_day_no += static::$daysMonthJalali[$i];
}
$j_day_no += $j_d - 1;
$g_day_no = $j_day_no + 79;
$gy = (1600 + 400 * static::div($g_day_no, 146097)); # 146097 = (365 * 400 + 400 / 4 - 400 / 100 + 400 / 400)
$g_day_no = $g_day_no % 146097;
$leap = 1;
if ($g_day_no >= 36525) { # 36525 = (365 * 100 + 100 / 4)
$g_day_no --;
$gy += (100 * static::div($g_day_no, 36524)); # 36524 = (365 * 100 + 100 / 4 - 100 / 100)
$g_day_no = $g_day_no % 36524;
if ($g_day_no >= 365) {
$g_day_no ++;
} else {
$leap = 0;
}
}
$gy += (4 * static::div($g_day_no, 1461)); # 1461 = (365 * 4 + 4 / 4)
$g_day_no %= 1461;
if ($g_day_no >= 366) {
$leap = 0;
$g_day_no --;
$gy += static::div($g_day_no, 365);
$g_day_no = ($g_day_no % 365);
}
for ($i = 0; $g_day_no >= (static::$daysMonthGregorian[$i] + ($i == 1 && $leap)); $i ++) {
$g_day_no -= (static::$daysMonthGregorian[$i] + ($i == 1 && $leap));
}
return array($gy, $i + 1, $g_day_no + 1);
}
/**
* integer division
*
* @param int $a
* @param int $b
* @return int
*/
private static function div($a, $b) {
return ~~($a / $b);
}
/**
* return day number from first day of year
*
* @param int $month
* @param int $day
* @return type
* @since 5.0.0
*/
public function daysYear($month, $day) {
$days = 0;
for ($i = 0; $i < $month; $i ++) {
$days += static::$daysMonthJalali[$i];
}
return ($days + $day);
}
/**
* return last day of month
*
* @param int $year
* @param int $month
* @return int
*/
public static function daysMonthJalali($year,$month) {
if(static::isLeapYear($year) && ($month == 12))
return 30;
$month = intval($month);
return static::$daysMonthJalali[$month-1];
}
}