programing

PHP에서 첫 요일을 얻으시겠습니까?

sourcejob 2022. 9. 27. 23:49
반응형

PHP에서 첫 요일을 얻으시겠습니까?

지정 ★★★★★★MM-dd-yyyy아, 아, 아, 아, 아, 아, 아, 아, 아, 아, 아, 아, 아, 아, 아, 아, 아, 아, 아, 아, 아, 아, 아, 아, 아!

이게 제가 쓰는...

$day = date('w');
$week_start = date('m-d-Y', strtotime('-'.$day.' days'));
$week_end = date('m-d-Y', strtotime('+'.(6-$day).' days'));

$day에는 요일을 나타내는 0 ~6 의 숫자가 포함되어 있습니다(일요일 = 0, 월요일 = 1 등).
$week_start에는 현재 주의 일요일 날짜가 mm-dd-yyyy로 포함됩니다.
$week_end에는 이번 주 토요일의 날짜가 mm-dd-yyyy로 포함됩니다.

매우 사용하기 쉬운 기능:

echo date("Y-m-d", strtotime('monday this week')), "\n";   

echo date("Y-m-d", strtotime('sunday this week')), "\n";

PHP 버전에 따라 약간 다릅니다.

5.3.0 - 5.6.6, php7@20140507 - 20150301, hhvm-3.3.1 - 3.5.1 출력

2015-03-16
2015-03-22

4.3.5 - 5.2.17의 출력

2015-03-23
2015-03-22

4.3.0 - 4.3.4의 출력

2015-03-30
2015-03-29

엣지 케이스에서의 비교

이번 주처럼 상대적인 서술은 그들만의 맥락을 가지고 있다.다음은 이번 주 월요일과 일요일(월요일 또는 일요일)의 출력을 보여 줍니다.

$date = '2015-03-16'; // monday
echo date("Y-m-d", strtotime('monday this week', strtotime($date))), "\n";   
echo date("Y-m-d", strtotime('sunday this week', strtotime($date))), "\n";

$date = '2015-03-22'; // sunday
echo date("Y-m-d", strtotime('monday this week', strtotime($date))), "\n";   
echo date("Y-m-d", strtotime('sunday this week', strtotime($date))), "\n";

다시 말씀드리지만 PHP 버전에 따라 약간 다릅니다.

5.3.0 - 5.6.6, php7@20140507 - 20150301, hhvm-3.3.1 - 3.5.1 출력

2015-03-16
2015-03-22
2015-03-23
2015-03-29

4.3.5~5.0.5, 5.2.0~5.2.17의 출력

2015-03-16
2015-03-22
2015-03-23
2015-03-22

5.1.0 - 5.1.6 출력

2015-03-23
2015-03-22
2015-03-23
2015-03-29

4.3.0 - 4.3.4의 출력

2015-03-23
2015-03-29
2015-03-30
2015-03-29
strtotime('this week', time());

시간을 바꿉니다().다음 주 일요일/지난 주 월요일 방법은 현재 날짜가 일요일/월요일이면 작동하지 않습니다.

심플화:

<?php    
$dateTime = new \DateTime('2020-04-01');
$monday = clone $dateTime->modify(('Sunday' == $dateTime->format('l')) ? 'Monday last week' : 'Monday this week');
$sunday = clone $dateTime->modify('Sunday this week');    
?>

출처 : PHP 매뉴얼

NB: 일부 사용자의 코멘트에 따라 $date Time 값이 변경됩니다.

$givenday = date("w", mktime(0, 0, 0, MM, dd, yyyy));

를 알 수 .0과 =일요일6= 됩니다. 원하는날을 할 수 .여기서 원하는 날짜를 거꾸로 계산할 수 있습니다.

이 질문에는 적절한 Date Time 답변이 필요합니다.-

function firstDayOfWeek($date)
{
    $day = DateTime::createFromFormat('m-d-Y', $date);
    $day->setISODate((int)$day->format('o'), (int)$day->format('W'), 1);
    return $day->format('m-d-Y');
}

var_dump(firstDayOfWeek('06-13-2013'));

출력:-

string '06-10-2013' (length=10)

이것은 연도 경계와 윤년을 다룰 것이다.

편집: 다음 링크는 지정된 버전의 PHP에서 더 이상 실행되지 않습니다.Strtotime의 신뢰성을 향상시키는 PHP 5.6에서 실행되지만 완벽하지는 않습니다!이 표의 결과는 PHP 5.6의 라이브 결과입니다.

여기에서는 일관된 기준 프레임을 결정할 때 strtotime의 이상한 행동을 분석합니다.

http://gamereplays.org/reference/strtotime.php

기본적으로 다음 문자열만 현재 어떤 요일에 전화를 걸든 동일한 날짜를 확실하게 제공합니다.

strtotime("next monday");
strtotime("this sunday");
strtotime("last sunday"); 

월요일을 주의 첫 번째 요일로 가정하면 다음과 같습니다.

echo date("M-d-y", strtotime('last monday', strtotime('next week', time())));

다음 코드는 원하는 날짜 형식만 사용하여 모든 사용자 지정 날짜와 함께 사용할 수 있습니다.

$custom_date = strtotime( date('d-m-Y', strtotime('31-07-2012')) ); 
$week_start = date('d-m-Y', strtotime('this week last monday', $custom_date));
$week_end = date('d-m-Y', strtotime('this week next sunday', $custom_date));
echo '<br>Start: '. $week_start;
echo '<br>End: '. $week_end;

PHP 5.2.17로 코드를 테스트했습니다.결과:

Start: 30-07-2012
End: 05-08-2012

이건 어때?

$first_day_of_week = date('m-d-Y', strtotime('Last Monday', time()));
$last_day_of_week = date('m-d-Y', strtotime('Next Sunday', time()));

이것은 어떤 날짜로부터도 요일의 첫날과 마지막 요일을 얻기 위해 사용하는 것입니다.이 경우 월요일이 일주일의 첫 번째 요일입니다.

$date = date('Y-m-d') // you can put any date you want
$nbDay = date('N', strtotime($date));
$monday = new DateTime($date);
$sunday = new DateTime($date);
$monday->modify('-'.($nbDay-1).' days');
$sunday->modify('+'.(7-$nbDay).' days');

여기서는 일요일을 첫 번째 요일로, 토요일을 한 주의 마지막 요일로 생각하고 있습니다.

$m = strtotime('06-08-2012');  
$today =   date('l', $m);  
$custom_date = strtotime( date('d-m-Y', $m) );   
if ($today == 'Sunday') {  
   $week_start = date("d-m-Y", $m);  
} else {  
  $week_start = date('d-m-Y', strtotime('this week last sunday', $custom_date));  
}  

if ($today == 'Saturday') {  
  $week_end = date("d-m-Y", $m);
} else {  
  $week_end = date('d-m-Y', strtotime('this week next saturday', $custom_date));  
}
echo '<br>Start: '. $week_start;  
echo '<br>End: '. $week_end;  

출력:

5월 8일
2012년 8일

이건 어때?

$day_of_week = date('N', strtotime($string_date));
$week_first_day = date('Y-m-d', strtotime($string_date . " - " . ($day_of_week - 1) . " days"));
$week_last_day = date('Y-m-d', strtotime($string_date . " + " . (7 - $day_of_week) . " days"));

쓰세요.date($format, strtotime($date,' LAST SUNDAY + 1 DAY'));

이것을 시험해 보세요.

function week_start_date($wk_num, $yr, $first = 1, $format = 'F d, Y')
{
    $wk_ts  = strtotime('+' . $wk_num . ' weeks', strtotime($yr . '0101'));
    $mon_ts = strtotime('-' . date('w', $wk_ts) + $first . ' days', $wk_ts);
    return date($format, $mon_ts);
}

$sStartDate = week_start_date($week_number, $year);
$sEndDate   = date('F d, Y', strtotime('+6 days', strtotime($sStartDate)));

(이 포럼 스레드에서)

이것이 제가 찾은 솔루션 중 가장 짧고 읽기 쉬운 것입니다.

    <?php
    $weekstart = strtotime('monday this week');
    $weekstop = strtotime('sunday this week 23:59:59');
    //echo date('d.m.Y H:i:s', $weekstart) .' - '. date('d.m.Y H:i:s', $weekstop);
    ?>

strtotimenew DateTime()->getTimestamp().

$monday = date('d-m-Y',strtotime('last monday',strtotime('next monday',strtotime($date))));

다음 주 월요일부터 받고 다음 주 월요일의 '마지막 월요일'을 받아야 합니다.따라서 지정된 날짜가 월요일인 경우 지난 주 월요일이 아닌 동일한 날짜가 반환됩니다.

$string_date = '2019-07-31';
echo $day_of_week = date('N', strtotime($string_date));
echo $week_first_day = date('Y-m-d', strtotime($string_date . " - " . ($day_of_week - 1) . " days"));
echo $week_last_day = date('Y-m-d', strtotime($string_date . " + " . (7 - $day_of_week) . " days"));

주어진 PHP 버전 5.3 이전 함수는 주어진 날짜(이 경우 2013-02-03)의 첫 번째 요일을 제공합니다.

<?php
  function startOfWeek($aDate){
    $d=strtotime($aDate);
    return strtotime(date('Y-m-d',$d).' - '.date("w",$d).' days');
  }

  echo(date('Y-m-d',startOfWeek("2013-02-07")).'
');
?>
$today_day = date('D'); //Or add your own date
$start_of_week = date('Ymd');
$end_of_week = date('Ymd');

if($today_day != "Mon")
    $start_of_week = date('Ymd', strtotime("last monday"));

if($today_day != "Sun")
                    $end_of_week = date('Ymd', strtotime("next sunday"));

월요일을 주의 시작으로 하는 경우는, 다음과 같이 실시합니다.

$date = '2015-10-12';
$day = date('N', strtotime($date));
$week_start = date('Y-m-d', strtotime('-'.($day-1).' days', strtotime($date)));
$week_end = date('Y-m-d', strtotime('+'.(7-$day).' days', strtotime($date)));

이를 위한 현명한 방법은 PHP가 시간대 차이와 일광 절약 시간(DST)을 처리할 수 있도록 하는 것입니다.어떻게 하는지 보여줄게.

이 함수는 월요일부터 금요일까지 모든 요일을 생성합니다(근무 주일을 생성하는 데 유용합니다).

class DateTimeUtilities {
    public static function getPeriodFromMondayUntilFriday($offset = 'now') {
        $now = new \DateTimeImmutable($offset, new \DateTimeZone('UTC'));
        $today = $now->setTime(0, 0, 1);

        $daysFromMonday = $today->format('N') - 1;

        $monday = $today->sub(new \DateInterval(sprintf('P%dD', $daysFromMonday)));
        $saturday = $monday->add(new \DateInterval('P5D'));

        return new \DatePeriod($monday, new \DateInterval('P1D'), $saturday);
    }
}

foreach (DateTimeUtilities::getPeriodFromMondayUntilFriday() as $day) {
    print $day->format('c');
    print PHP_EOL;
}

그러면 현재 주의 월요일-금요일 날짜가 반환됩니다.날짜에 합니다.DateTimeUtilities ::getPeriodFromMondayUntilFriday 해서하다

foreach (DateTimeUtilities::getPeriodFromMondayUntilFriday('2017-01-02T15:05:21+00:00') as $day) {
    print $day->format('c');
    print PHP_EOL;
}

//prints 
//2017-01-02T00:00:01+00:00
//2017-01-03T00:00:01+00:00
//2017-01-04T00:00:01+00:00
//2017-01-05T00:00:01+00:00
//2017-01-06T00:00:01+00:00

작전부 요청대로 월요일에만 관심이 있나?

$monday = DateTimeUtilities::getPeriodFromMondayUntilFriday('2017-01-02T15:05:21+00:00')->getStartDate()->format('c');
print $monday;
// prints
//2017-01-02T00:00:01+00:00

결과를 사용하여 날짜를 해석합니다.

date('N', strptime('%m-%d-%g', $dateString));
<?php
/* PHP 5.3.0 */

date_default_timezone_set('America/Denver'); //Set apprpriate timezone
$start_date = strtotime('2009-12-15'); //Set start date

//Today's date if $start_date is a Sunday, otherwise date of previous Sunday
$today_or_previous_sunday = mktime(0, 0, 0, date('m', $start_date), date('d', $start_date), date('Y', $start_date)) - ((date("w", $start_date) ==0) ? 0 : (86400 * date("w", $start_date)));

//prints 12-13-2009 (month-day-year)
echo date('m-d-Y', $today_or_previous_sunday);

?>

(주의: 질문의 MM, dd 및 yyyy는 표준 php date 형식의 구문이 아닙니다.무슨 뜻인지 알 수 없기 때문에 ISO year-month-day를 사용하여 $start_date를 설정합니다.)

저는 이 질문에 여러 번 맞닥뜨렸지만 날짜 함수가 이 문제를 더 쉽게 또는 더 명확하게 만들지 못한다는 사실에 항상 놀랐습니다.은 PHP5를 DateTime 링크:

/**
 * @param DateTime $date A given date
 * @param int $firstDay 0-6, Sun-Sat respectively
 * @return DateTime
 */
function getFirstDayOfWeek(DateTime $date, $firstDay = 0) {
    $offset = 7 - $firstDay;
    $ret = clone $date;
    $ret->modify(-(($date->format('w') + $offset) % 7) . 'days');
    return $ret;
}

원래 날짜가 변경되지 않도록 복제해야 합니다.

또 다른 방법으로는...

$year = '2014';
$month = '02';
$day = '26';

$date = DateTime::createFromFormat('Y-m-d H:i:s', $year . '-' . $month . '-' . $day . '00:00:00');
$day = date('w', $date->getTimestamp());

// 0=Sunday 6=Saturday
if($day!=0){

   $newdate = $date->getTimestamp() - $day * 86400;  //86400 seconds in a day

   // Look for DST change 
   if($old = date('I', $date->getTimestamp()) != $new = date('I', $newdate)){
       if($old == 0){
           $newdate -= 3600;  //3600 seconds in an hour
       } else {
           $newdate += 3600;
       }
   }

   $date->setTimestamp($newdate);
}

echo $date->format('D Y-m-d H:i:s');

현재 주의 첫 번째 날(월요일)을 얻는 가장 쉬운 방법은 다음과 같습니다.

strtotime("next Monday") - 604800;

여기서 604800은 1주일 동안의 초수(60*60*24*7)입니다.

이 코드는 다음 주 월요일에 적용되어 1주일 동안 감소합니다.이 코드는 어느 요일에나 정상적으로 동작합니다.오늘이 월요일이라도.

내 시간대가 호주이고 그 시간대가 호주라는 것을 생각하면 나는 이것이 상당히 좌절감을 느꼈다.strtotime()츠미야

만약 오늘이 일요일이라면strtotime("monday this week")다음 날 다시 찾아올게요.

이 문제를 해결하려면:

주의:이것은 호주/영국 날짜에만 유효합니다.

$startOfWeek = (date('l') == 'Monday') ? date('d/m/Y 00:00') : date('d/m/Y', strtotime("last monday 00:00"));
$endOfWeek = (date('l') == 'Sunday') ? date('d/m/Y 23:59:59') : date('d/m/Y', strtotime("sunday 23:59:59"));

여기 지난주 첫날과 마지막 날을 위한 라이너 한 대가 있습니다.DateTime물건.

$firstDay = (new \DateTime())->modify(sprintf('-%d day', date('w') + 7))
                             ->setTime(0, 0, 0);
$lastDay = (new \DateTime())->modify(sprintf('-%d day', date('w') + 1))
                            ->setTime(23, 59, 59);

그럼 어떻게 되는 거죠?

$date = "2013-03-18"; 
$searchRow = date("d.m.Y", strtotime('last monday',strtotime($date." + 1 day")));
echo "for date " .$date ." we get this monday: " ;echo $searchRow; echo '<br>';

최선의 방법은 아니지만 시험을 봤는데 이번 주에 있으면 월요일이 맞고 월요일이면 월요일이 됩니다.

언급URL : https://stackoverflow.com/questions/1897727/get-first-day-of-week-in-php

반응형