简体   繁体   中英

How to get day number of the week of current month's first day in PHP

I want to get day number of week of the current month. For example

to day

Sep. 1st, Monday 

should return 1

Oct. 1st, Wednesday

should return 3

21.11.2014

should return 6

Try this:

var_dump(date('N', mktime(0, 0, 0, date('n'), 1)));

It's not clear from your question whether your input is a string or whether the function should assume the current month/year that is right now.

$weekdayNumber = date('N', strtotime($datestring));

This returns 1:

date('N', strtotime('Sep. 1st, Monday'));

This returns 3:

date('N', strtotime('Oct. 1st, Wednesday'));

As mentioned in the comment date('N', ...) can be used to achieve this:

<?php
date_default_timezone_set('UTC');

echo date('N', strtotime('First day of month')) . PHP_EOL;
echo date('N', strtotime('Sep. 1st, Monday')) . PHP_EOL;
echo date('N', strtotime('Oct. 1st, Wednesday')) . PHP_EOL;

Or see here: http://codepad.org/mr6itbjK

I suppose you actually don't know the weekday ('Monday', 'Wednesday') so all of the following would also work:

echo date('N', strtotime('Sep. 1st')); // this assumes "this year"
echo date('N', strtotime('Sep. 1st 2014'));
echo date('N', strtotime('2014-09-01')); 

echo date('N', strtotime('Oct. 1st')); // this assumes "this year"
echo date('N', strtotime('Oct. 1st 2014'));
echo date('N', strtotime('2014-10-01'));

see also http://php.net/manual/en/function.strtotime.php

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM