搜尋
首頁後端開發php教程 php 时隔日期工具类

php 时间日期工具类

<?php
DateTimeUtils::addDate('2012-12-01',1,'y');
DateTimeUtils::getWeekDay('2012/10/01','/');
DateTimeUtils::isLeapYear('2012');
class DateTimeUtils {
	/**
	 * Checks for leap year, returns true if it is. No 2-digit year check. Also
	 * handles julian calendar correctly.
	 * @param integer $year year to check
	 * @return boolean true if is leap year
	 */
	public static function isLeapYear($year)
	{
		$year = self::digitCheck($year);
		if ($year % 4 != 0)
			return false;

		if ($year % 400 == 0)
			return true;
		// if gregorian calendar (>1582), century not-divisible by 400 is not leap
		else if ($year > 1582 && $year % 100 == 0 )
			return false;
		return true;
	}

	/**
	 * Fix 2-digit years. Works for any century.
	 * Assumes that if 2-digit is more than 30 years in future, then previous century.
	 * @param integer $y year
	 * @return integer change two digit year into multiple digits
	 */
	protected static function digitCheck($y)
	{
		if ($y < 100){
			$yr = (integer) date("Y");
			$century = (integer) ($yr /100);

			if ($yr%100 > 50) {
				$c1 = $century + 1;
				$c0 = $century;
			} else {
				$c1 = $century;
				$c0 = $century - 1;
			}
			$c1 *= 100;
			// if 2-digit year is less than 30 years in future, set it to this century
			// otherwise if more than 30 years in future, then we set 2-digit year to the prev century.
			if (($y + $c1) < $yr+30) $y = $y + $c1;
			else $y = $y + $c0*100;
		}
		return $y;
	}

	/**
	 * Returns 4-digit representation of the year.
	 * @param integer $y year
	 * @return integer 4-digit representation of the year
	 */
	public static function get4DigitYear($y)
	{
		return self::digitCheck($y);
	}
	/**
	 * Checks to see if the year, month, day are valid combination.
	 * @param integer $y year
	 * @param integer $m month
	 * @param integer $d day
	 * @return boolean true if valid date, semantic check only.
	 */
	public static function isValidDate($y,$m,$d)
	{
		return checkdate($m, $d, $y);
	}
	public static function checkDate($date, $separator = "-") { //检查日期是否合法日期
		$dateArr = explode ($separator, $date);
		if (is_numeric ( $dateArr [0] ) && is_numeric ( $dateArr [1] ) && is_numeric ( $dateArr [2] )) {
			return checkdate ( $dateArr [1], $dateArr [2], $dateArr [0] );
		}
		return false;
	}
	/**
	 * Checks to see if the hour, minute and second are valid.
	 * @param integer $h hour
	 * @param integer $m minute
	 * @param integer $s second
	 * @param boolean $hs24 whether the hours should be 0 through 23 (default) or 1 through 12.
	 * @return boolean true if valid date, semantic check only.
	 * @since 1.0.5
	 */
	public static function isValidTime($h,$m,$s,$hs24=true)
	{
		if($hs24 && ($h < 0 || $h > 23) || !$hs24 && ($h < 1 || $h > 12)) return false;
		if($m > 59 || $m < 0) return false;
		if($s > 59 || $s < 0) return false;
		return true;
	}
	public static function checkTime($time, $separator = ":") { //检查时间是否合法时间  
		$timeArr = explode ($separator, $time );
		if (is_numeric ( $timeArr [0] ) && is_numeric ( $timeArr [1] ) && is_numeric ( $timeArr [2] )) {
			if (($timeArr [0] >= 0 && $timeArr [0] <= 23) && ($timeArr [1] >= 0 && $timeArr [1] <= 59) && ($timeArr [2] >= 0 && $timeArr [2] <= 59))
				return true;
			else
				return false;
		}
		return false;
	}
	
	public static function addDate($date, $int, $unit = "d") { //日期的增加
		$dateArr = explode ( "-", $date );
		$value [$unit] = $int;
		return date ( "Y-m-d", mktime ( 0, 0, 0, $dateArr [1] + $value ['m'], $dateArr [2] + $value ['d'], $dateArr [0] + $value ['y'] ) );
	
	}
	
	public static function addDayTimestamp($ntime, $aday) { //取当前时间后几天,天数增加单位为1
		$dayst = 3600 * 24;
		$oktime = $ntime + ($aday * $dayst);
		return $oktime;
	}
	
	public static function dateDiff($date1, $date2, $unit = "d") { //时间比较函数,返回两个日期相差几秒、几分钟、几小时或几天  
		switch ($unit) {
			case 's' :
				$dividend = 1;
				break;
			case 'i' :
				$dividend = 60;
				break;
			case 'h' :
				$dividend = 3600;
				break;
			case 'd' :
				$dividend = 86400;
				break;
			default :
				$dividend = 86400;
		}
		$time1 = strtotime ( $date1 );
		$time2 = strtotime ( $date2 );
		if ($time1 && $time2)
			return ( float ) ($time1 - $time2) / $dividend;
		return false;
	}
	//2011-12-06  =>
	public static function getWeekDay($date, $separator = "-") { //计算出给出的日期是星期几
		$dateArr = explode ($separator, $date);
		return date ( "w", mktime ( 0, 0, 0, $dateArr [1], $dateArr [2], $dateArr [0] ) );
	}
	
	public static function floorTime($seconds) { //让日期显示为:XX天XX年以前 
		$times = '';
		$days = floor ( ($seconds / 86400) % 30 );
		$hours = floor ( ($seconds / 3600) % 24 );
		$minutes = floor ( ($seconds / 60) % 60 );
		$seconds = floor ( $seconds % 60 );
		if ($seconds >= 1)
			$times .= $seconds . '秒';
		if ($minutes >= 1)
			$times = $minutes . '分钟 ' . $times;
		if ($hours >= 1)
			$times = $hours . '小时 ' . $times;
		if ($days >= 1)
			$times = $days . '天';
		if ($days > 30)
			return false;
		$times .= '前';
		return str_replace ( " ", '', $times );
	}
	
	public static function transDateToChs($date) {
		if (empty ( $date ))
			return '今日';
		$y = date ( 'Y', strtotime ( $date ) );
		$m = date ( 'm', strtotime ( $date ) );
		$d = date ( 'd', strtotime ( $date ) );
		return $y . '年' . $m . '月' . $d . '日';
	}
	
	// 08/31/2004 => 2004-08-31
	public static function TransDateUI($datestr, $type = 'Y-m-d') {
		if ($datestr == Null)
			return Null;
		$target = $datestr;
		$arr_date = preg_split ( "/\//", $target );
		$monthstr = $arr_date [0];
		$daystr = $arr_date [1];
		$yearstr = $arr_date [2];
		$result = date ( $type, mktime ( 0, 0, 0, $monthstr, $daystr, $yearstr ) );
		return $result;
	}
	
	// 12/20/2004 10:55 AM => 2004-12-20 10:55:00
	public static function TransDateTimeUI($datestr, $type = 'Y-m-d H:i:s') {
		if ($datestr == Null)
			return Null;
		$target = $datestr;
		$arr_date = preg_split ( "/\/|\s|:/", $target );
		$monthstr = $arr_date [0];
		$daystr = $arr_date [1];
		$yearstr = $arr_date [2];
		$hourstr = $arr_date [3];
		$minutesstr = $arr_date [4];
		$result = date ( $type, mktime ( $hourstr, $minutesstr, 0, $monthstr, $daystr, $yearstr ) );
		return $result;
	}
	
	// 2004-08-31 => 08/31/2004
	public static function TransDateDB($datestr, $type = 'm/d/Y') {
		if ($datestr == Null)
			return Null;
		if ($datestr == '0000-00-00')
			return Null;
		$target = $datestr;
		$arr_date = preg_split ( "/-/", $target );
		$monthstr = $arr_date [1];
		$daystr = $arr_date [2];
		$yearstr = $arr_date [0];
		$result = date ( $type, mktime ( 0, 0, 0, $monthstr, $daystr, $yearstr ) );
		return $result;
	}
	
	// 2004-08-31 10:55:00 => 12/20/2004 10:55 AM 
	public static function TransDateTimeDB($datestr, $type = 'm/d/Y h:i A') {
		if ($datestr == Null)
			return Null;
		$target = $datestr;
		$arr_date = preg_split ( "/-|\s|:/", $target );
		$monthstr = $arr_date [1];
		$daystr = $arr_date [2];
		$yearstr = $arr_date [0];
		$hourstr = $arr_date [3];
		$minutesstr = $arr_date [4];
		$secondstr = $arr_date [5];
		$result = date ( $type, mktime ( $hourstr, $minutesstr, $secondstr, $monthstr, $daystr, $yearstr ) );
		return $result;
	}
}
?>
?

陳述
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
如何使PHP應用程序更快如何使PHP應用程序更快May 12, 2025 am 12:12 AM

tomakephpapplicationsfaster,關注台詞:1)useopcodeCachingLikeLikeLikeLikeLikePachetoStorePreciledScompiledScriptbyTecode.2)MinimimiedAtabaseSqueriSegrieSqueriSegeriSybysequeryCachingandeffeftExting.3)Leveragephp7 leveragephp7 leveragephp7 leveragephpphp7功能forbettercodeefficy.4)

PHP性能優化清單:立即提高速度PHP性能優化清單:立即提高速度May 12, 2025 am 12:07 AM

到ImprovephPapplicationspeed,關注台詞:1)啟用opcodeCachingwithapCutoredUcescriptexecutiontime.2)實現databasequerycachingingusingpdotominiminimizedatabasehits.3)usehttp/2tomultiplexrequlexrequestsandreduceconnection.4 limitesclection.4.4

PHP依賴注入:提高代碼可檢驗性PHP依賴注入:提高代碼可檢驗性May 12, 2025 am 12:03 AM

依赖注入(DI)通过显式传递依赖关系,显著提升了PHP代码的可测试性。1)DI解耦类与具体实现,使测试和维护更灵活。2)三种类型中,构造函数注入明确表达依赖,保持状态一致。3)使用DI容器管理复杂依赖,提升代码质量和开发效率。

PHP性能優化:數據庫查詢優化PHP性能優化:數據庫查詢優化May 12, 2025 am 12:02 AM

DatabasequeryoptimizationinPHPinvolvesseveralstrategiestoenhanceperformance.1)Selectonlynecessarycolumnstoreducedatatransfer.2)Useindexingtospeedupdataretrieval.3)Implementquerycachingtostoreresultsoffrequentqueries.4)Utilizepreparedstatementsforeffi

簡單指南:帶有PHP腳本的電子郵件發送簡單指南:帶有PHP腳本的電子郵件發送May 12, 2025 am 12:02 AM

phpisusedforsenderemailsduetoitsbuilt-inmail()函數andsupportivelibrariesLikePhpMailerAndSwiftMailer.1)usethemail()functionForbasiceMails,butithasimails.2)butithasimail.2)

PHP性能:識別和修復瓶頸PHP性能:識別和修復瓶頸May 11, 2025 am 12:13 AM

PHP性能瓶颈可以通过以下步骤解决:1)使用Xdebug或Blackfire进行性能分析,找出问题所在;2)优化数据库查询并使用缓存,如APCu;3)使用array_filter等高效函数优化数组操作;4)配置OPcache进行字节码缓存;5)优化前端,如减少HTTP请求和优化图片;6)持续监控和优化性能。通过这些方法,可以显著提升PHP应用的性能。

PHP的依賴注入:快速摘要PHP的依賴注入:快速摘要May 11, 2025 am 12:09 AM

依賴性注射(DI)InphpisadesignPatternthatManages和ReducesClassDeptions,增強量強制性,可驗證性和MATIALWINABIOS.ItallowSpasspassingDepentenciesLikEdenciesLikedAbaseConnectionStoclasseconnectionStoclasseSasasasasareTers,interitationAseTestingEaseTestingEaseTestingEaseTestingEasingAndScalability。

提高PHP性能:緩存策略和技術提高PHP性能:緩存策略和技術May 11, 2025 am 12:08 AM

cachingimprovesphpermenceByStorcyResultSofComputationsorqucrouctationsorquctationsorquickretrieval,reducingServerLoadAndenHancingResponsetimes.feftectivestrategiesinclude:1)opcodecaching,whereStoresCompiledSinmememorytssinmemorytoskipcompliation; 2)datacaching datacachingsingMemccachingmcachingmcachings

See all articles

熱AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover

AI Clothes Remover

用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool

Undress AI Tool

免費脫衣圖片

Clothoff.io

Clothoff.io

AI脫衣器

Video Face Swap

Video Face Swap

使用我們完全免費的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱門文章

熱工具

禪工作室 13.0.1

禪工作室 13.0.1

強大的PHP整合開發環境

Dreamweaver Mac版

Dreamweaver Mac版

視覺化網頁開發工具

MantisBT

MantisBT

Mantis是一個易於部署的基於Web的缺陷追蹤工具,用於幫助產品缺陷追蹤。它需要PHP、MySQL和一個Web伺服器。請查看我們的演示和託管服務。

SublimeText3漢化版

SublimeText3漢化版

中文版,非常好用

SublimeText3 英文版

SublimeText3 英文版

推薦:為Win版本,支援程式碼提示!