php date 1 month earlier - php

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?

Related

Dummy php date compare

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.

Calculate day of month with month, year, day of week and number of week

How can I calculate the day of month in PHP with giving month, year, day of week and number of week.
Like, if I have September 2013 and day of week is Friday and number of week is 2, I should get 6. (9/6/2013 is Friday on the 2nd week.)
One way to achieve this is using relative formats for strtotime().
Unfortunately, it's not as straightforward as:
strtotime('Friday of second week of September 2013');
In order for the weeks to work as you mentioned, you need to call strtotime() again with a relative timestamp.
$first_of_month_timestamp = strtotime('first day of September 2013');
$second_week_friday = strtotime('+1 week, Friday', $first_of_month_timestamp);
echo date('Y-m-d', $second_week_friday); // 2013-09-13
Note: Since the first day of the month starts on week one, I've decremented the week accordingly.
I was going to suggest to just use strtotime() in this fashion:
$ts = strtotime('2nd friday of september 2013');
echo date('Y-m-d', $ts), PHP_EOL;
// outputs: 2013-09-13
It seems that this is not how you want the calendar to behave? But it is following a (proper) standard :)
This way its a little longer and obvious but it works.
/* INPUT */
$month = "September";
$year = "2013";
$dayWeek= "Friday";
$week = 2;
$start = strtotime("{$year}/{$month}/1"); //get first day of that month
$result = false;
while(true) { //loop all days of month to find expected day
if(date("w", $start) == $week && date("l", $start) == $dayWeek) {
$result = date("d", $start);
break;
}
$start += 60 * 60 * 24;
}
var_dump($result); // string(2) "06"

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 DateTime::modify adding and subtracting months

I've been working a lot with the DateTime class and recently ran into what I thought was a bug when adding months. After a bit of research, it appears that it wasn't a bug, but instead working as intended. According to the documentation found here:
Example #2 Beware when adding or
subtracting months
<?php
$date = new DateTime('2000-12-31');
$date->modify('+1 month');
echo $date->format('Y-m-d') . "\n";
$date->modify('+1 month');
echo $date->format('Y-m-d') . "\n";
?>
The above example will output:
2001-01-31
2001-03-03
Can anyone justify why this isn't considered a bug?
Furthermore does anyone have any elegant solutions to correct the issue and make it so +1 month will work as expected instead of as intended?
Why it's not a bug:
The current behavior is correct. The following happens internally:
+1 month increases the month number (originally 1) by one. This makes the date 2010-02-31.
The second month (February) only has 28 days in 2010, so PHP auto-corrects this by just continuing to count days from February 1st. You then end up at March 3rd.
How to get what you want:
To get what you want is by: manually checking the next month. Then add the number of days next month has.
I hope you can yourself code this. I am just giving what-to-do.
PHP 5.3 way:
To obtain the correct behavior, you can use one of the PHP 5.3's new functionality that introduces the relative time stanza first day of. This stanza can be used in combination with next month, fifth month or +8 months to go to the first day of the specified month. Instead of +1 month from what you're doing, you can use this code to get the first day of next month like this:
<?php
$d = new DateTime( '2010-01-31' );
$d->modify( 'first day of next month' );
echo $d->format( 'F' ), "\n";
?>
This script will correctly output February. The following things happen when PHP processes this first day of next month stanza:
next month increases the month number (originally 1) by one. This makes the date 2010-02-31.
first day of sets the day number to 1, resulting in the date 2010-02-01.
Here is another compact solution entirely using DateTime methods, modifying the object in-place without creating clones.
$dt = new DateTime('2012-01-31');
echo $dt->format('Y-m-d'), PHP_EOL;
$day = $dt->format('j');
$dt->modify('first day of +1 month');
$dt->modify('+' . (min($day, $dt->format('t')) - 1) . ' days');
echo $dt->format('Y-m-d'), PHP_EOL;
It outputs:
2012-01-31
2012-02-29
This may be useful:
echo Date("Y-m-d", strtotime("2013-01-01 +1 Month -1 Day"));
// 2013-01-31
echo Date("Y-m-d", strtotime("2013-02-01 +1 Month -1 Day"));
// 2013-02-28
echo Date("Y-m-d", strtotime("2013-03-01 +1 Month -1 Day"));
// 2013-03-31
echo Date("Y-m-d", strtotime("2013-04-01 +1 Month -1 Day"));
// 2013-04-30
echo Date("Y-m-d", strtotime("2013-05-01 +1 Month -1 Day"));
// 2013-05-31
echo Date("Y-m-d", strtotime("2013-06-01 +1 Month -1 Day"));
// 2013-06-30
echo Date("Y-m-d", strtotime("2013-07-01 +1 Month -1 Day"));
// 2013-07-31
echo Date("Y-m-d", strtotime("2013-08-01 +1 Month -1 Day"));
// 2013-08-31
echo Date("Y-m-d", strtotime("2013-09-01 +1 Month -1 Day"));
// 2013-09-30
echo Date("Y-m-d", strtotime("2013-10-01 +1 Month -1 Day"));
// 2013-10-31
echo Date("Y-m-d", strtotime("2013-11-01 +1 Month -1 Day"));
// 2013-11-30
echo Date("Y-m-d", strtotime("2013-12-01 +1 Month -1 Day"));
// 2013-12-31
My solution to the problem:
$startDate = new \DateTime( '2015-08-30' );
$endDate = clone $startDate;
$billing_count = '6';
$billing_unit = 'm';
$endDate->add( new \DateInterval( 'P' . $billing_count . strtoupper( $billing_unit ) ) );
if ( intval( $endDate->format( 'n' ) ) > ( intval( $startDate->format( 'n' ) ) + intval( $billing_count ) ) % 12 )
{
if ( intval( $startDate->format( 'n' ) ) + intval( $billing_count ) != 12 )
{
$endDate->modify( 'last day of -1 month' );
}
}
I agree with the sentiment of the OP that this is counter-intuitive and frustrating, but so is determining what +1 month means in the scenarios where this occurs. Consider these examples:
You start with 2015-01-31 and want to add a month 6 times to get a scheduling cycle for sending an email newsletter. With the OP's initial expectations in mind, this would return:
2015-01-31
2015-02-28
2015-03-31
2015-04-30
2015-05-31
2015-06-30
Right away, notice that we are expecting +1 month to mean last day of month or, alternatively, to add 1 month per iteration but always in reference to the start point. Instead of interpreting this as "last day of month" we could read it as "31st day of next month or last available within that month". This means that we jump from April 30th to May 31st instead of to May 30th. Note that this is not because it is "last day of month" but because we want "closest available to date of start month."
So suppose one of our users subscribes to another newsletter to start on 2015-01-30. What is the intuitive date for +1 month? One interpretation would be "30th day of next month or closest available" which would return:
2015-01-30
2015-02-28
2015-03-30
2015-04-30
2015-05-30
2015-06-30
This would be fine except when our user gets both newsletters on the same day. Let's assume that this is a supply-side issue instead of demand-side We're not worried that the user will be annoyed with getting 2 newsletters in the same day but instead that our mail servers can't afford the bandwidth for sending twice as many newsletters. With that in mind, we return to the other interpretation of "+1 month" as "send on the second to last day of each month" which would return:
2015-01-30
2015-02-27
2015-03-30
2015-04-29
2015-05-30
2015-06-29
Now we've avoided any overlap with the first set, but we also end up with April and June 29th, which certainly does match our original intuitions that +1 month simply should return m/$d/Y or the attractive and simple m/30/Y for all possible months. So now let's consider a third interpretation of +1 month using both dates:
Jan. 31st
2015-01-31
2015-03-03
2015-03-31
2015-05-01
2015-05-31
2015-07-01
Jan. 30th
2015-01-30
2015-03-02
2015-03-30
2015-04-30
2015-05-30
2015-06-30
The above has some issues. February is skipped, which could be a problem both supply-end (say if there is a monthly bandwidth allocation and Feb goes to waste and March gets doubled up on) and demand-end (users feel cheated out of Feb and perceive the extra March as attempt to correct mistake). On the other hand, notice that the two date sets:
never overlap
are always on the same date when that month has the date (so the Jan. 30 set looks pretty clean)
are all within 3 days (1 day in most cases) of what might be considered the "correct" date.
are all at least 28 days (a lunar month) from their successor and predecessor, so very evenly distributed.
Given the last two sets, it would not be difficult to simply roll back one of the dates if it falls outside of the actual following month (so roll back to Feb 28th and April 30th in the first set) and not lose any sleep over the occasional overlap and divergence from the "last day of month" vs "second to last day of month" pattern. But expecting the library to choose between "most pretty/natural", "mathematical interpretation of 02/31 and other month overflows", and "relative to first of month or last month" is always going to end with someone's expectations not being met and some schedule needing to adjust the "wrong" date to avoid the real-world problem that the "wrong" interpretation introduces.
So again, while I also would expect +1 month to return a date that actually is in the following month, it is not as simple as intuition and given the choices, going with math over the expectations of web developers is probably the safe choice.
Here's an alternative solution that is still as clunky as any but I think has nice results:
foreach(range(0,5) as $count) {
$new_date = clone $date;
$new_date->modify("+$count month");
$expected_month = $count + 1;
$actual_month = $new_date->format("m");
if($expected_month != $actual_month) {
$new_date = clone $date;
$new_date->modify("+". ($count - 1) . " month");
$new_date->modify("+4 weeks");
}
echo "* " . nl2br($new_date->format("Y-m-d") . PHP_EOL);
}
It's not optimal but the underlying logic is : If adding 1 month results in a date other than the expected next month, scrap that date and add 4 weeks instead. Here are the results with the two test dates:
Jan. 31st
2015-01-31
2015-02-28
2015-03-31
2015-04-28
2015-05-31
2015-06-28
Jan. 30th
2015-01-30
2015-02-27
2015-03-30
2015-04-30
2015-05-30
2015-06-30
(My code is a mess and wouldn't work in a multi-year scenario. I welcome anyone to rewrite the solution with more elegant code so long as the underlying premise is kept intact, i.e. if +1 month returns a funky date, use +4 weeks instead.)
In conjunction with shamittomar's answer, it could then be this for adding months "safely":
/**
* Adds months without jumping over last days of months
*
* #param \DateTime $date
* #param int $monthsToAdd
* #return \DateTime
*/
public function addMonths($date, $monthsToAdd) {
$tmpDate = clone $date;
$tmpDate->modify('first day of +'.(int) $monthsToAdd.' month');
if($date->format('j') > $tmpDate->format('t')) {
$daysToAdd = $tmpDate->format('t') - 1;
}else{
$daysToAdd = $date->format('j') - 1;
}
$tmpDate->modify('+ '. $daysToAdd .' days');
return $tmpDate;
}
I made a function that returns a DateInterval to make sure that adding a month shows the next month, and removes the days into the after that.
$time = new DateTime('2014-01-31');
echo $time->format('d-m-Y H:i') . '<br/>';
$time->add( add_months(1, $time));
echo $time->format('d-m-Y H:i') . '<br/>';
function add_months( $months, \DateTime $object ) {
$next = new DateTime($object->format('d-m-Y H:i:s'));
$next->modify('last day of +'.$months.' month');
if( $object->format('d') > $next->format('d') ) {
return $object->diff($next);
} else {
return new DateInterval('P'.$months.'M');
}
}
This is an improved version of Kasihasi's answer in a related question. This will correctly add or subtract an arbitrary number of months to a date.
public static function addMonths($monthToAdd, $date) {
$d1 = new DateTime($date);
$year = $d1->format('Y');
$month = $d1->format('n');
$day = $d1->format('d');
if ($monthToAdd > 0) {
$year += floor($monthToAdd/12);
} else {
$year += ceil($monthToAdd/12);
}
$monthToAdd = $monthToAdd%12;
$month += $monthToAdd;
if($month > 12) {
$year ++;
$month -= 12;
} elseif ($month < 1 ) {
$year --;
$month += 12;
}
if(!checkdate($month, $day, $year)) {
$d2 = DateTime::createFromFormat('Y-n-j', $year.'-'.$month.'-1');
$d2->modify('last day of');
}else {
$d2 = DateTime::createFromFormat('Y-n-d', $year.'-'.$month.'-'.$day);
}
return $d2->format('Y-m-d');
}
For example:
addMonths(-25, '2017-03-31')
will output:
'2015-02-28'
I found a shorter way around it using the following code:
$datetime = new DateTime("2014-01-31");
$month = $datetime->format('n'); //without zeroes
$day = $datetime->format('j'); //without zeroes
if($day == 31){
$datetime->modify('last day of next month');
}else if($day == 29 || $day == 30){
if($month == 1){
$datetime->modify('last day of next month');
}else{
$datetime->modify('+1 month');
}
}else{
$datetime->modify('+1 month');
}
echo $datetime->format('Y-m-d H:i:s');
Here is an implementation of an improved version of Juhana's answer in a related question:
<?php
function sameDateNextMonth(DateTime $createdDate, DateTime $currentDate) {
$addMon = clone $currentDate;
$addMon->add(new DateInterval("P1M"));
$nextMon = clone $currentDate;
$nextMon->modify("last day of next month");
if ($addMon->format("n") == $nextMon->format("n")) {
$recurDay = $createdDate->format("j");
$daysInMon = $addMon->format("t");
$currentDay = $currentDate->format("j");
if ($recurDay > $currentDay && $recurDay <= $daysInMon) {
$addMon->setDate($addMon->format("Y"), $addMon->format("n"), $recurDay);
}
return $addMon;
} else {
return $nextMon;
}
}
This version takes $createdDate under the presumption that you are dealing with a recurring monthly period, such as a subscription, that started on a specific date, such as the 31st. It always takes $createdDate so late "recurs on" dates won't shift to lower values as they are pushed forward thru lesser-valued months (e.g., so all 29th, 30th or 31st recur dates won't eventually get stuck on the 28th after passing thru a non-leap-year February).
Here is some driver code to test the algorithm:
$createdDate = new DateTime("2015-03-31");
echo "created date = " . $createdDate->format("Y-m-d") . PHP_EOL;
$next = sameDateNextMonth($createdDate, $createdDate);
echo " next date = " . $next->format("Y-m-d") . PHP_EOL;
foreach(range(1, 12) as $i) {
$next = sameDateNextMonth($createdDate, $next);
echo " next date = " . $next->format("Y-m-d") . PHP_EOL;
}
Which outputs:
created date = 2015-03-31
next date = 2015-04-30
next date = 2015-05-31
next date = 2015-06-30
next date = 2015-07-31
next date = 2015-08-31
next date = 2015-09-30
next date = 2015-10-31
next date = 2015-11-30
next date = 2015-12-31
next date = 2016-01-31
next date = 2016-02-29
next date = 2016-03-31
next date = 2016-04-30
$ds = new DateTime();
$ds->modify('+1 month');
$ds->modify('first day of this month');
If you just want to avoid skipping a month you can perform something like this to get the date out and run a loop on the next month reducing the date by one and rechecking until a valid date where $starting_calculated is a valid string for strtotime (i.e. mysql datetime or "now"). This finds the very end of the month at 1 minute to midnight instead of skipping the month.
$start_dt = $starting_calculated;
$next_month = date("m",strtotime("+1 month",strtotime($start_dt)));
$next_month_year = date("Y",strtotime("+1 month",strtotime($start_dt)));
$date_of_month = date("d",$starting_calculated);
if($date_of_month>28){
$check_date = false;
while(!$check_date){
$check_date = checkdate($next_month,$date_of_month,$next_month_year);
$date_of_month--;
}
$date_of_month++;
$next_d = $date_of_month;
}else{
$next_d = "d";
}
$end_dt = date("Y-m-$next_d 23:59:59",strtotime("+1 month"));
Extension for DateTime class which solves problem of adding or subtracting months
https://gist.github.com/66Ton99/60571ee49bf1906aaa1c
If using strtotime() just use $date = strtotime('first day of +1 month');
I needed to get a date for 'this month last year' and it becomes unpleasant quite quickly when this month is February in a leap year. However, I believe this works... :-/ The trick seems to be to base your change on the 1st day of the month.
$this_month_last_year_end = new \DateTime();
$this_month_last_year_end->modify('first day of this month');
$this_month_last_year_end->modify('-1 year');
$this_month_last_year_end->modify('last day of this month');
$this_month_last_year_end->setTime(23, 59, 59);
$month = 1; $year = 2017;
echo date('n', mktime(0, 0, 0, $month + 2, -1, $year));
will output 2 (february). will work for other months too.
$current_date = new DateTime('now');
$after_3_months = $current_date->add(\DateInterval::createFromDateString('+3 months'));
For days:
$after_3_days = $current_date->add(\DateInterval::createFromDateString('+3 days'));
Important:
The method add() of DateTime class modify the object value so after calling add() on a DateTime Object it returns the new date object and also it modify the object it self.
you can actually do it with just date() and strtotime() as well. For example to add 1 month to todays date:
date("Y-m-d",strtotime("+1 month",time()));
if you are wanting to use the datetime class thats fine too but this is just as easy. more details here
$date = date('Y-m-d', strtotime("+1 month"));
echo $date;

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