2010-09-10 5 views

Répondre

9

Utilisez cette fonction:

<?php 
    /** 
    * 
    * Gets the first weekday of that month and year 
    * 
    * @param int The day of the week (0 = sunday, 1 = monday ... , 6 = saturday) 
    * @param int The month (if false use the current month) 
    * @param int The year (if false use the current year) 
    * 
    * @return int The timestamp of the first day of that month 
    * 
    **/ 
    function get_first_day($day_number=1, $month=false, $year=false) 
    { 
    $month = ($month === false) ? strftime("%m"): $month; 
    $year = ($year === false) ? strftime("%Y"): $year; 

    $first_day = 1 + ((7+$day_number - strftime("%w", @mktime(0,0,0,$month, 1, $year)))%7); 

    return @mktime(0,0,0,$month, $first_day, $year); 
    } 

    // this will output the first saturday of january 2007 (Sat 06-01-2007) 
    echo strftime("%a %d-%m-%Y", get_first_day(6, 1, 2007)); 
?> 

Crédits: php.net


[EDIT]: Une autre façon courte:

Utilisez strtotime() comme ceci:

$month = 1; 
$year = 2007; 

echo date('d/M/Y',strtotime('First Saturday '.date('F o', @mktime(0,0,0, $month, 1, $year)))); 

Cette sortie:

06/Jan/2007 
+0

salut Shamit bro .. d'abord tout le monde pour votre réponse. mais dans les deux cas il montre un avertissement comme Avertissement: mktime() attend le paramètre 4 pour être long, chaîne donnée ... je suis entièrement nouveau à php alors pourriez-vous m'aider à trier ce .. thx. – bsrreddy

+0

@bsrreddy, j'ai mis à jour les deux codes pour supprimer les avertissements. Essayez maintenant. – shamittomar

+0

hmm ... le code fonctionne bien bro. mais le résultat n'est pas correct. J'ai choisi 02-jan-2010 dans mon calendrier où cette date est un premier samedi de ce mois. mais le résultat est 03/Jan/2009 où il devrait être 02/jan/2009. – bsrreddy

0

Voici une doublure:

$firstSat = strtotime('first Saturday', strtotime("$month $year")); 

Test:

foreach(array("Jan","Feb","Nov","Dec") as $month) 
{ 
    $year = '2017'; 
    echo "$month, $year"; 
    $firstSat = strtotime('first Saturday', strtotime("$month $year")); 
    $date = date('Y-M-d', $firstSat); 
    echo " $firstSat $date <br>" ; 
} 

Sorties:

Jan, 2017 1483747200 2017-Jan-07 
Feb, 2017 1486166400 2017-Feb-04 
Nov, 2017 1509753600 2017-Nov-04 
Dec, 2017 1512172800 2017-Dec-02 
Questions connexes