Dato un MM-dd-yyyyformato di data , qualcuno può aiutarmi a ottenere il primo giorno della settimana?
DateTimesoluzione e la maggior parte delle risposte non la fornisce. =)
Dato un MM-dd-yyyyformato di data , qualcuno può aiutarmi a ottenere il primo giorno della settimana?
DateTimesoluzione e la maggior parte delle risposte non la fornisce. =)
Risposte:
Ecco cosa sto usando ...
$day = date('w');
$week_start = date('m-d-Y', strtotime('-'.$day.' days'));
$week_end = date('m-d-Y', strtotime('+'.(6-$day).' days'));
$ day contiene un numero da 0 a 6 che rappresenta il giorno della settimana (domenica = 0, lunedì = 1, ecc.).
$ week_start contiene la data della domenica della settimana corrente come mm-gg-aaaa.
$ week_end contiene la data del sabato della settimana corrente come mm-gg-aaaa.
strtotime('this week', time());
Sostituisci ora (). I metodi della prossima domenica / ultimo lunedì non funzioneranno quando il giorno corrente è domenica / lunedì.
$monday = strtotime('last monday', strtotime('tomorrow'));
this weeknon funziona se devi avere sempre un inizio settimana precedente, ma il commento di @ LewisBuckley lo fa.
time()è facoltativo se si desidera specificare oggi.
strtotimeFunzione molto semplice da usare :
echo date("Y-m-d", strtotime('monday this week')), "\n";
echo date("Y-m-d", strtotime('sunday this week')), "\n";
È leggermente diverso tra le versioni PHP :
2015-03-16
2015-03-22
2015-03-23
2015-03-22
2015-03-30
2015-03-29
Le descrizioni relative come questa settimana hanno il loro contesto. Quanto segue mostra l'output per questa settimana il lunedì e la domenica quando è un lunedì o una domenica:
$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";
E poi è un po 'diverso tra le versioni PHP :
2015-03-16
2015-03-22
2015-03-23
2015-03-29
2015-03-16
2015-03-22
2015-03-23
2015-03-22
2015-03-23
2015-03-22
2015-03-23
2015-03-29
2015-03-23
2015-03-29
2015-03-30
2015-03-29
Mantienilo semplice:
<?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');
?>
Fonte : manuale PHP
NB: come alcuni utenti hanno commentato il valore $ dateTime verrà modificato.
$dateTime = new \DateTime('2012-05-14');
DateTimeclasse principale , il che significa che il codice funzionerà anche se hai un'altra classe chiamata DateTimenello spazio dei nomi corrente.
$givenday = date("w", mktime(0, 0, 0, MM, dd, yyyy));
Questo ti dà il giorno della settimana della data stessa dove 0= domenica e 6= sabato. Da lì puoi semplicemente calcolare all'indietro fino al giorno che desideri.
Questa domanda necessita di una buona risposta DateTime : -
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'));
Produzione:-
string '06-10-2013' (length=10)
Questo affronterà i confini degli anni e gli anni bisestili.
MODIFICA: il link sottostante non è più in esecuzione sulla versione di PHP dichiarata. Funziona su PHP 5.6 che migliora l'affidabilità di strtotime, ma non è perfetto! I risultati nella tabella sono risultati in tempo reale da PHP 5.6.
Per quello che vale, ecco una ripartizione del comportamento traballante di strtotime quando si determina un quadro di riferimento coerente:
http://gamereplays.org/reference/strtotime.php
Fondamentalmente solo queste stringhe ti daranno in modo affidabile la stessa data, indipendentemente dal giorno della settimana in cui ti trovi quando le chiami:
strtotime("next monday");
strtotime("this sunday");
strtotime("last sunday");
Il codice seguente dovrebbe funzionare con qualsiasi data personalizzata, utilizza solo il formato della data desiderato.
$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;
Ho testato il codice con PHP 5.2.17 Risultati:
Start: 30-07-2012
End: 05-08-2012
Supponendo che lunedì sia il primo giorno della settimana, funziona:
echo date("M-d-y", strtotime('last monday', strtotime('next week', time())));
Questo è ciò che sto usando per ottenere il primo e l'ultimo giorno della settimana da qualsiasi data . In questo caso, il lunedì è il primo giorno della settimana ...
$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');
Qui sto considerando la domenica come primo e il sabato come ultimo giorno della settimana.
$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;
Produzione :
Inizio: 05-08-2012
Fine: 11-08-2012
Cosa ne pensi di questo?
$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"));
Prova questo:
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)));
(da questo thread del forum )
Questa è la soluzione più breve e più leggibile che ho trovato:
<?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);
?>
strtotimeè più veloce di new DateTime()->getTimestamp().
Basta usare date($format, strtotime($date,' LAST SUNDAY + 1 DAY'));
Data la versione PHP precedente alla 5.3, la seguente funzione fornisce un primo giorno della settimana della data specificata (in questo caso - domenica, 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"));
$monday = date('d-m-Y',strtotime('last monday',strtotime('next monday',strtotime($date))));
Devi prima ottenere il prossimo lunedì, quindi ottenere l '"ultimo lunedì" del prossimo lunedì. Quindi, se la data specificata è lunedì, restituirà la stessa data non la scorsa settimana lunedì.
Se vuoi che il lunedì sia l'inizio della tua settimana, fai questo:
$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)));
Un modo intelligente per farlo è lasciare che PHP gestisca le differenze di fuso orario e l'ora legale (DST). Lascia che ti mostri come farlo.
Questa funzione genererà tutti i giorni dal lunedì al venerdì inclusi (utile per generare giorni feriali lavorativi):
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;
}
Questo restituirà i datetimes dal lunedì al venerdì per la settimana corrente. Per fare lo stesso per una data arbitraria, passare una data come parametro a DateTimeUtilities ::getPeriodFromMondayUntilFriday, quindi:
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
Interessato solo a lunedì, come ha chiesto l'OP?
$monday = DateTimeUtilities::getPeriodFromMondayUntilFriday('2017-01-02T15:05:21+00:00')->getStartDate()->format('c');
print $monday;
// prints
//2017-01-02T00:00:01+00:00
Analizzi la data usando strptime()e usi date()sul risultato:
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);
?>
(Nota: MM, dd e yyyy nella domanda non sono sintassi del formato di data php standard - Non posso essere sicuro di cosa si intende, quindi ho impostato $ start_date con ISO anno-mese-giorno)
Un altro modo per farlo ...
$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');
Il modo più semplice per ottenere il primo giorno (lunedì) della settimana corrente è:
strtotime("next Monday") - 604800;
dove 604800 - è il conteggio dei secondi in 1 settimana (60 * 60 * 24 * 7).
Questo codice viene ricevuto il lunedì successivo e diminuito per 1 settimana. Questo codice funzionerà bene in qualsiasi giorno della settimana. Anche se oggi è lunedì.
Ho trovato questo abbastanza frustrante dato che il mio fuso orario è australiano e così via strtotime() odia le date del Regno Unito.
Se il giorno corrente è una domenica, strtotime("monday this week")tornerà il giorno successivo.
Per ovviare a questo:
Attenzione : questo è valido solo per le date australiane / britanniche
$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"));
Ecco una riga per il primo giorno della scorsa settimana e l'ultimo giorno della scorsa settimana come DateTimeoggetto.
$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);
$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"));
Mi sono imbattuto in questa domanda alcune volte e ho sempre sorpreso che le funzioni di data non rendessero questo più facile o più chiaro. Ecco la mia soluzione per PHP5 che utilizza la DateTimeclasse:
/**
* @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;
}
Necessario clonare per evitare di alterare la data originale.
Che dire:
$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>';
Non è il modo migliore, ma ho provato e se sono in questa settimana ottengo il lunedì corretto, e se sono di lunedì lo riceverò quel lunedì.