Dummy php date compare - php

I'm dummy and dont know how to compare date's.
I need to do link unclickable when date is less or equal today.
This is actullay not complete code, full code prints this week monday to sunday. Im try to do calendar what print 1 week each time and each day it print time 9am to 17pm.
$toDay = date("m-d-y");
$first = date('m-d-Y', strtotime('Last Monday +'.$d.' days'));
//This sunday + 1 week
$last = date('m-d-Y', strtotime('Next Sunday +'.$d.' days'));
//print week number
**if($first <= $toDay() && $tomorrow <= $toDay)**
{
echo"<p class='list_header'>". $tomorrow."</p>";
//Looping time 9 to 17
for($time_start = 9; $time_start <= 17; $time_start+=2)
{
echo "<li style='background-color:red'><a href='#'>".$time_start."</a></li>";
}
}

You can use timestamp method to compare the time value in php.

Related

How can I make date("W") start in Sunday and end on saturday? [duplicate]

I need to get week number in php where week should be calculated from sunday. By default its from monday. Please help me to find a way how to get week number considering sunday as starting day.
In php manual
ISO-8601 week number of year, weeks starting on Monday (added in PHP 4.1.0)
But I need to get week number of year, weeks starting on sunday.
thanks
Try this:
$week = intval(date('W'));
if (date('w') == 0) { // 0 = Sunday
$week++;
}
echo $week;
Not sure if the logic is right though;
The first solution is not correct on Jan 01, 2017 or any year that begins on a Sunday.
Try this:
$date = date('Y-m-d');
echo strftime("%U", strtotime($date ) );
To expand on silkfire answer and allow for it wrapping around years
if($date->format('w') == 0){
if(date('W',strtotime($date->format('Y')."-12-31"))==52 and $date->format('W') == 52){
$week = 1;
}
elseif(date('W',strtotime($date->format('Y')."-12-31"))==53 and $date->format('W') == 53){
$week = 1;
}
else{
$week++;
}
}
Try this one. to get sunday day must -1 day.
$date = "2015-05-25";
echo date("W", strtotime("-1 day",strtotime($date)));
You should try with strftime
$week_start = new DateTime();
$week = strftime("%U"); //this gets you the week number starting Sunday
$week_start->setISODate(2012,$week,0); //return the first day of the week with offset 0
echo $week_start -> format('d-M-Y'); //and just prints with formatting
I solved this like this:
function getWeekOfYear( DateTime $date ) {
$dayOfweek = intval( $date->format('w') );
if( $dayOfweek == 0 ) {
$date->add(new DateInterval('P1D'));
}
$weekOfYear = intval( $date->format('W') );
return $weekOfYear;
}
I know this topic is old, but this is a shorter way to do it with elvis operator and "+7 day" expression for strtotime():
$week=date("W",strtotime(date("w")==1?"+7 day":"+0 day"));
if $date("w") returns true means today is a day between tuesday and sunday (1-6), so, we can return today week ('today').
if returns false, it means is monday (0), so, we should return the next day ('+1 week').
This way we don't need to care about last or first day of year or check if current year has 52 or 53 weeks.
Edited: the previous answer (and others in this topic) doesn't work for this year because januray 1st is monday, so, it needs to be 1 week ago (-1 week) excluding sunday (day 6).
date("W",strtotime(date("w")?'-7 day':'+0 day'));
I think a condition asking if januray 1st is monday could work, but I didn't test it yet, I will come back with an answer later
For a custom day you could use this:
$date = strtotime('2018-04-30'); // (it is monday)
if(date("w",strtotime(date('Y',$date).'-01-01'))==1){ // if first day of year is monday
$week = strtotime(date('w',$date)?"-7 day":"+0 day",$date); // and today is sunday, sub a week
$week = date("W",$week);
}else{ // if is not monday
$week = strtotime(date('w',$date)==1?"+7 day":"+0 day",$date); // and today is monday, add a week
$week = date("W",$week);
}
Building on #silkfire's answer:
$year = date('Y');
$week_no = date('W');
if (date('w') == 0) { // 0 = Sunday
$week_no++;
}
// We shifted the week but the week still starts on a Monday.
$weekStartDate = new DateTime();
$weekStartDate->setISODate($year,$week_no);
// Shift start date to Sunday
$weekStartDate->add(DateInterval::createFromDateString('-1 day'));
Tested in php 5.6 Debian 7
function getWeekNumber(\DateTime $_date)
{
$week = intval($_date->format('W'));
if(intval($_date->format('w')) == 0) {
$week = intval($_date->format('W')) == ( 52 + intval($_date->format('L')) ) ? 1 : $week + 1;
}
return $week;
}
I needed to ADD day instead of subtracting to get Alghi Fari's answer to work.
$date = "2022-11-13";
echo date("W", strtotime("+1 day",strtotime($date)));

How to get every 15th and last day of the month in PHP

I am trying to figure out on how to set my dates to every 15th and end of month only...what i'm getting so far is only +15 days from my current date..
current date = date today.LOGIC: if the current day is less than 15 then the start date of the loop is on the end of the month then if the current day is equal or greater than 15 then the start date of the loop is on the 15th. so in my case my current date is Nov 9 so the First output should be Nov 30.
$y = 1;
while ($y <= $num_term) { // num_term is equal to the number of output
$month_line = strtotime("15 day", strtotime("$month_sched"));
$day = date("d", $month_line);
$month_int = date("M-d", $month_line);
}
Output:
Nov 24`<br />`
Dec 9`<br />`
Dec 24`<br />`
Could anybody help me... thanks :)
Try this
Find the first day of month
Find the Last Day of month as Lalji Nakum told
Check your date with 15th Day of month Like example bellow
if($today < $hDay){
echo 'Start : '. date("t-m-Y");
}else if ($today >= $hDay){
echo 'Start :'. $hDay;
}
Here,
1. $today will the current date,
2. $hDay will be the 15th day of the month like 15 Nov
Here is the sample code
echo 'First day of month '.
$fDay = date('01-m-Y');
echo '<br> 15th day of month '.
$hDay = date('d-m-Y', (strtotime($fDay)+ (86400 * 15)));
echo '<br> Last Day of month '.
$lDay = date("t-m-Y");
echo '<br> Current day '.
$today = date('d-m-Y');
//$today = date('d-m-Y', strtotime($hDay)+86400 );
echo '<br>';
if($today < $hDay){
echo 'Start : '. $lDay = date("t-m-Y");
}else if ($today >= $hDay){
echo 'Start :'. $hDay;
}
You can get total number of days in month by
<?php
$a_date = "2015-11-09";
echo totaldays = date("t", strtotime($a_date));
?>
You can get current day from current date :
<?php
echo curday = date('d');
if(curday==totaldays){
echo "lastday";
}
if(curday==15)
{
echo "15th day";
}
?>
find 15th: strtotime($month_sched." +14 day");
find last day of month: strtotime($month_sched." next month - 1 hour");
Please try the following code:
<?php
$y=1;
$num_term = 10;
//start date
$month_sched = date("2012-02-01");
while($y <= $num_term) {
//15th
$month_line_15 = strtotime($month_sched." +14 day");
//last day of month
$month_line_last = strtotime($month_sched." next month - 1 hour");
$day = date("M-d", $month_line_15);
$month_int = date("M-d", $month_line_last);
$month_sched = date("Y-m-d",strtotime($month_sched." +1month"));
$y++;
}
Tested.
PHPFiddle
You can use mktime with 0 and 15 as value for the day:
$a = date("m-d", mktime(0,0,0,$month,0));
$b = date("m-d", mktime(0,0,0,$month,15));
This will give you the last day of the previous month and the 15. of $month
More than enough answers possible for this one. I would like to contribute an answer as well.
$beginDate = new DateTime('15 January');
// clone start date
$endDate = clone $beginDate;
// Add 1 year to start date
$endDate->modify('+1 year');
// Increase with an interval of one month
$dateInterval = new DateInterval('P1M');
$dateRange = new DatePeriod($beginDate, $dateInterval, $endDate);
foreach ($dateRange as $day) {
echo $day->format('Y-m-d')."<br />"; // 15th
echo $day->format('Y-m-t')."<br />"; // Last month day
}
References
PHP Manual - DateTime
PHP Manual - DateInterval
PHP Manual - DatePeriod
PHP Manual - clone

Getting first / last date of the week

Is it possible to get the first / last date of a week using PHP's Relative Date Time format?
I've tried to do:
date_default_timezone_set('Europe/Amsterdam');
$date = new DateTime();
$date->modify('first day of this week'); // to get the current week's first date
echo $date->format('Y-m-d'); // outputs 2011-12-19
$date->modify('first day of week 50'); // to get the first date of any week by weeknumber
echo $date->format('Y-m-d'); // outputs 2011-12-18
$date->modify('last day of this week'); // to get the current week's last date
echo $date->format('Y-m-d'); // outputs 2011-12-17
$date->modify('last day of week 50'); // to get the last date of any week by weeknumber
echo $date->format('Y-m-d'); // outputs 2011-12-18
As you can see it doesn't output the correct dates.
According to the docs this should be possible if I'm correct.
Am I doing something terrible wrong?
EDIT
I need to use PHP's DateTime for dates in the far future.
UPDATE
It gets only stranger now. I've done some more testing.
Windows PHP 5.3.3
2011-12-01
Warning: DateTime::modify() [datetime.modify]: Failed to parse time string (first day of week 50) at position 13 (w): The timezone could not be found in the database in C:\Users\Gerrie\Desktop\ph\Websites\Charts\www.charts.com\public\index.php on line 9
2011-12-01
2011-11-30
Warning: DateTime::modify() [datetime.modify]: Failed to parse time string (last day of week 50) at position 12 (w): The timezone could not be found in the database in C:\Users\Gerrie\Desktop\ph\Websites\Charts\www.charts.com\public\index.php on line 15
2011-11-30
Linux 5.3.8
2011-12-01
2011-12-01
2011-11-30
2011-11-30
I'm a big fan of using the Carbon library, which makes this sort of thing really easy. For example:
use Carbon\Carbon;
$monday = Carbon::now()->startOfWeek()
$sunday = Carbon::now()->endOfWeek()
Or, if you'd prefer to have Sunday be the first day of your week:
use Carbon\Carbon;
Carbon::setWeekStartsAt(Carbon::SUNDAY);
Carbon::setWeekEndsAt(Carbon::SATURDAY);
$sunday = Carbon::now()->startOfWeek()
$saturday = Carbon::now()->endOfWeek()
According to docs the format strings "first day of" and "last day of" are only allowed for months, not for weeks. See http://www.php.net/manual/en/datetime.formats.relative.php
If you combine first and last day of with a week statement the result either blows the parser or is something that you did not expect (usually the first or last day of a month, not a week).
The difference that you see between Win and Linux is probably only because of different error reporting settings.
To get the first and last day of the current week use:
$date->modify('this week');
$date->modify('this week +6 days');
To get the first and last day of week 50 use:
$date->setISODate(2011, 50);
$date->setISODate(2011, 50, 7);
EDIT:
If you want to use the modify method for absolute week numbers you have to use the formats defined in http://www.php.net/manual/en/datetime.formats.compound.php:
$date->modify('2011W50');
$date->modify('2011W50 +6 days');
if first day of week is Monday
$date->modify('Monday this week');
else if first day is Sunday
$date->modify('Sunday this week');
because in different countries first day of week maybe Monday or Sunday
This is what I am using to get the first and last day of the week from any date.
In this case, monday is the first day of the week...
$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');
function getweek_first_last_date($date)
{
$cur_date = strtotime($date); // Change to whatever date you need
// Get the day of the week: Sunday = 0 to Saturday = 6
$dotw = date('w', $cur_date);
if($dotw>1)
{
$pre_monday = $cur_date-(($dotw-1)*24*60*60);
$next_sunday = $cur_date+((7-$dotw)*24*60*60);
}
else if($dotw==1)
{
$pre_monday = $cur_date;
$next_sunday = $cur_date+((7-$dotw)*24*60*60);
}
else if($dotw==0)
{
$pre_monday =$cur_date -(6*24*60*60);;
$next_sunday = $cur_date;
}
$date_array = array();
$date_array['start_date_of_week'] = $pre_monday;
$date_array['end_date_of_week'] = $next_sunday;
return $date_array;
}
$date = '2013-12-22';
getweek_first_last_date($date);
Output :
$array_of_week = Array
(
[start_date_of_week] => 1387152000
[end_date_of_week] => 1387670400
)
$start_date =date('d/m/Y', $array_of_week['start_date_of_week'])
<code>
function getlastweek_first_last_date()
{
$cur_date = strtotime(date('Y-m-d')); // Change to whatever date you need
// Get the day of the week: Sunday = 0 to Saturday = 6
$previousweekcurdate = $cur_date - (7*24*3600);
$cur_date = $previousweekcurdate;
$dotw = date('w', $cur_date);
if($dotw>1)
{
$pre_sunday = $cur_date-(($dotw-1)*24*60*60) - (24*60*60);
$next_satday = $cur_date+((7-$dotw)*24*60*60)- (24*60*60);
}
else if($dotw==1)
{
$pre_sunday = $cur_date- (24*60*60);
$next_satday = $cur_date+((7-$dotw)*24*60*60)- (24*60*60);
}
else if($dotw==0)
{
$pre_sunday =$cur_date -(6*24*60*60)- (24*60*60);
$next_satday = $cur_date- (24*60*60);
}
$pre_sunday = date('Y-m-d',$pre_sunday)." 00:00:00";
$next_satday = date('Y-m-d',$next_satday)." 23:59:59";
$date_array = array();
$date_array['sdoflw'] = $pre_sunday;
$date_array['edoflw'] = $next_satday;
return $date_array;
}
$date_array = getlastweek_first_last_date();
echo $start_date_of_week = $date_array['sdoflw'];
echo $end_date_of_week = $date_array['edoflw'];
</code>
Simply you can get the date as follows
first day of week is Monday
date('Y-m-d',strtotime('Monday this week'));
if first day is Sunday
date('Y-m-d',strtotime('Sunday this week'));

php date 1 month earlier

well im using this function to get the summer time in mexico.
function horarioVerano() {
$year = date("Y");
$ahora = strtotime(date("d-m-Y"));
$inicio_invierno = strtotime("last Sunday April $year");
//echo date('Y-m-d H:i:s', $inicio_invierno);
$fin_invierno = strtotime("last Sunday November $year");
//echo date('Y-m-d H:i:s', $fin_invierno);
if ($ahora > $inicio_invierno && $ahora <= $fin_invierno)
$num = 5;
else
$num = 6;
return $num;
}
but i always get the previous month date, if i echo date("Y-m-d",$inicio_invierno) i get 2011-03-27 and not 2011-04-24 as it should be , same for any other month i walways get the previous month
"last Sunday April $year" is parsed as "April $year" (which gives the first of the month) and then calculating "last Sunday" relative to that. If you want the last Sunday of April, say just that: "last Sunday of April $year". See the documentation for details.
What exactly is the point of this?
$ahora =strtotime(date("d-m-Y"));
You build a string-based date, then turn it back into a time value (which is an integer) with strtotime(). What a waste of CPU cycles. How about
$ahora = time();
instead?

Getting the date for current day in PHP

I want to get the date for current day in php. what i tried is here...
echo $x."<br>";
echo date("D",$x)."<br>";
But the output was
21-02-10
Thu
It is giving correct date but not the correct day value.Why..?
What I want day is the date for monday for the current week which can be generated on any day of the week. so what I did was, I'm taking the today's day and comparing with (Mon,Tue.... Sun) and respectively creating a timestamp using
case "Mon":
$startdate1=date("d-m-y");
$parts = explode('-',$startdate1);
$startdate2 = date('d-m-Y',mktime(0,0,0,$parts[1],($parts[0]+1),$parts[2]));
$startdate3 = date('d-m-Y',mktime(0,0,0,$parts[1],($parts[0]+2),$parts[2]));
$startdate4 = date('d-m-Y',mktime(0,0,0,$parts[1],($parts[0]+3),$parts[2]));
$startdate5 = date('d-m-Y',mktime(0,0,0,$parts[1],($parts[0]+4),$parts[2]));
$startdate6 = date('d-m-Y',mktime(0,0,0,$parts[1],($parts[0]+5),$parts[2]));
$startdate7 = date('d-m-Y',mktime(0,0,0,$parts[1],($parts[0]+6),$parts[2]));
$dates=array(1 => $startdate1,$startdate2,$startdate3,$startdate4,$startdate5,$startdate6,$startdate7);
$i=1;
while( $i <= 7 )
{
echo $dates[$i];
$i++;
}
break;
$date is the final array respective to today that has to be returned. Is there any other better method to do this operation.
I tried this to get current day.
echo date('l'); // output: current day.
How about this:
//today is monday
if (1 == date('N')){
$monday = time();
}else{
$monday = strtotime('last Monday');
}
for ($i = 0; $i < 7; $i++){
echo date('d-m-Y', $monday) . '<br>';
$monday = strtotime('tomorrow', $monday);
}
First find Monday, if it is not today, then print 7 dates
What I want day is the date for monday
for the current week which can be
generated on any day of the week.
That's what you want. $mday is the month day of this week's Monday. Nevermind if it's not positive, mktime will handle that right. $monday has the timestamp of the Monday's midnight.
$now = getdate();
$mday = $now['mday'] - ($now['wday'] + 6) % 7;
$monday = mktime(0, 0, 0, $now['mon'], $mday, $now['year']);
echo(date('d-m-y', $monday));
What i did to resolve it is used the date format ('d-m-Y') instead of ('d-m-y') in date function, which was causing the problem. Hence strtotime accepted the format and gave the correct result for
$t=date('d-m-Y');
echo date("D",strtotime($t));
I use the function date and path to it the "D" that refere to the current day , and it works with me
$today = date("D");
and to get the full info about the current date
$today = date("D M j G:i:s T Y"); // Sat Mar 10 17:16:18 MST 2001
what i tried is here...
echo date("D",$x)."<br>";
date expects a timestamp (int) value as the second parameter. Your $x is a string containing an ambiguous date format. Convert that date into a timestamp first, using strptime or strtotime and use the date function correctly to get the correct day value.
Regarding your second part, you don't need to (and shouldn't) check the day name to calculate the correct Monday, Tuesday etc. A more efficient approach is for example using strtotime to get last Monday etc.
You are likely passing a string as timestamp
echo $x."<br>";
echo date("D",$x)."<br>";
Remove $x and it will output the correct day or change it to
$x = '21-02-2010';
echo date('D', strtotime($x));

Categories