Home  >  Article  >  Backend Development  >  PHP code to get the first day of a month

PHP code to get the first day of a month

WBOY
WBOYOriginal
2016-07-25 08:56:581022browse
This article introduces the implementation code for obtaining the first day of a month based on the timestamp in PHP. Friends who are interested can study it.

The function given in this section can get the first day of the month. This function accepts a single, optional argument, which is a UNIX timestamp of any date. The function will then return the UNIX timestamp starting from the first day of the UNIX timestamp month. If there is no timestamp, this function defaults to the current month.

The resulting timestamp can be combined with PHP’s date function date() to perform any possible operation. Great for use as a calendar class, as well as getting the first day of any month.

Code:

<?php 

/* 
 * 
 * @ 返回某月第一天的时间戳 
 * 
 * @param INT Unix timestamp 
 * 
 * @return INT 
 * 
 */ 
function firstDayOfMonth($uts=null) 
{ 
    $today = is_null($uts) ? getDate() : getDate($uts); 
    $first_day = getdate(mktime(0,0,0,$today['mon'],1,$today['year'])); 
    return $first_day[0]; 
} 

 /*** example usage ***/ 

 /*** using the default ***/ 
 echo firstDayOfMonth(); 

 echo '<hr />'; 

 /*** using a timestamp ***/ 
 $long_ago = strtotime('April 16 2002'); 
 echo firstDayOfMonth($long_ago); 

?> 

Demo results: 1375279200 1017583200



Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn