nirosha rathnayaka
nirosha rathnayaka

Reputation: 198

How to check for the 1st day of an year in php

How to check weather today is the 1st day of the year or not in php.

edit: echo date('Y-m-d', strToTime('1/1 this year'));

this code gave me the result. Is this valid or is there better way than this.

Upvotes: 1

Views: 8595

Answers (9)

koe
koe

Reputation: 746

The date function has a z format character, which can be used for this:

$day_of_year = date('z');
// $day_of_year is 259 for the day I write this

Upvotes: 0

TigerTiger
TigerTiger

Reputation: 10806

If you were interested in the name of the first day of the year

echo date('l', strtotime('2012-01-01'));

OR

echo date('l', strtotime("first day of January 2012"));

Output:// Sunday

OR

just use -

echo (date('z') === 0) ? 'First day' : 'Not first day';

//z     The day of the year (starting from 0)   0 through 365

http://php.net/manual/en/function.date.php

http://www.php.net/manual/en/datetime.formats.relative.php

Upvotes: 0

Atul Rai
Atul Rai

Reputation: 350

You can do following :

echo date('Y-m-d', strtotime("first day of january " . date('Y')));

Upvotes: 0

Next Door Engineer
Next Door Engineer

Reputation: 2886

This should solve your problem and more!

<?php
$theDate = date("md"); 
if ($theDate=="0101") echo "It's A New Year!";
?>

Date() function formatting characters:

  • d - A numeric representation of the day of the month (0 - 31)
  • m - A numeric representation of the month of the year (1 - 12)
  • y - A numeric representation (two digit) of a year (99, 00, 01, 02)
  • H - 24 hour format current hour (00 - 23)
  • i - Minutes (00 - 59)
  • s - Seconds (00 - 59)

Upvotes: 0

Yabooo Yakhoo
Yabooo Yakhoo

Reputation: 27

The first day of the year is never different from 1/1/yyyy You can use strcmp or

$now=new DateTime();

then use getDay GetMonth from $now to evaluate

Upvotes: 0

donald123
donald123

Reputation: 5739

For further informations see http://php.net/date

<?php
 if(date('dm',mktime())=="0101")
    echo "fist day of year";
 else
    echo "not the first day";
?>

Upvotes: 0

palmic
palmic

Reputation: 1856

if (date('z') === 0) {
echo 'we have 1.1.'
}

http://php.net/manual/en/function.date.php

Upvotes: 2

Janis Elsts
Janis Elsts

Reputation: 764

You can get the day of the year by passing the format string 'z' do the built-in date() function. This will return '0' for the first day, '1' for the second, ... up to '365' for the last day of a (leap) year.

if ( date('z') === '0' ) {
    //Today is the first day of the year.
}

Upvotes: 7

Sammaye
Sammaye

Reputation: 43884

if(date('j') == '1' && date('n') == 1){
    // if first day of year
}

That will do it easily without any complicated date stuff that you would normally have to worry about.

Upvotes: 0

Related Questions