Problem:
You want to find the first date of the current month.
Solution:
There are few ways to get the first day of the current month. Let’s see the methods in detail.
Method 1: Using date() function
The example below is the simplest way to find out the first day of the current month.
<?php echo date("m-01-Y"); ?>
[wpdm_file id=122]
Output:
06-01-2014
How it works:
date() function returns a formatted date string according to the format given as the parameter. In the above example, the formatting characters are “m-01-Y”. Here, m is used to display month as number with leading zero. As this is June, the output displays 06. The, 01 is the first day of the current month. At last, Y displays the year in four digits.
Method 2: Using strtotime() function
strtotime() function can convert a date time string to its equivalent timestamp. This date time string must follow some predefined formats. One of the supported formats is relative formats which we’ll use here to define the first date of the current month. The following example shows how it is done-
<?php $timestamp = strtotime("first day of"); echo date("m-d-Y", $timestamp); ?>
[wpdm_file id=123]
Output:
06-01-2014
How it works:
The formatting parameter “first day of” which sets the first date of the current month is created from a relative formats.
Method 3: Using date() and modify() methods of DateTime class from SPL
Using the modify() methods, we can find the first date of the current month. See the following example-
<?php $dateObj = new DateTime('2014-06-02'); $dateObj->modify(first day of'); echo $dateObj ->format('m-d-Y'); ?>
[wpdm_file id=124]
Output:
06-01-2014
How it works:
Line 2 | It creates a new DateTIme object($dateObj) with the current date. |
Line 3 | The modify() method alters the date (which is existed as the DateTime object,$dateObj, that it uses) to the first date of the month of that date(2014-06-02). Here, the formatting parameter “first day of” sets the first date of the current month. It is the same date time formats that strtotime() function allows. See other date time formats that the modify() method allows. The modify() method returns the altered DateTIme object. |
Line 4 | The format() method format the DateTime object according to the format mentioned in its parameter and returns it. And, it is the output you see. |