Probably I do something wrong but I can't see the point of it ....
Today is a one day of the week. I must know - how many days have elapsed from last monday to today?
$date_1d = date('Y-m-d', strtotime ('last Monday'));
// last monday
$date_today = date('Y-m-d');
// actual date, today
$ile_dni = (strtotime($date_today) - strtotime($date_1d)) / (60*60*24);
// difference in days - how many days have elapsed from today to last monday
I have 2 identical scripts as above in the same directory on the same server
first said:
&date_1d = > 2012-03-19
$date_today => 2012-03-26
strtotime($date_today) = > 1332720000
strtotime($date_1d) = > 1332115200
$ile_dni = > 7
second said:
&date_1d = > 2012-03-19
$date_today => 2012-03-26
strtotime($date_today) = > 1332712800
strtotime($date_1d) = > 1332111600
$ile_dni = > 6.9583333333333
Couse the right answer is the first. And what to do with this situation?
use ceil() on the $ile_dni the differences are from the timestamp generated out of 'last Monday' and strtotime and i'm sure there is a better way to do this with date('N'), you could do
$ile_dni = date('N')-1;
if you wanted ile_dni to be 0 on monday, 1 on tuesday etc..
Did you run those two scripts at the same time? I'm guessing there's a timezone/DST issue going on. Note that your method of computing date differences is very vulnerable to these kinds of issues. If you're using PHP 5.3 or higher, use date_diff.
Related
I would like to know if a date is older than 1 day using Carbon.
I have tried:
$date = Carbon::parse($loggedUser->exchange_keys_last_time);
$now = Carbon::now();
var_dump($date);
var_dump($now);
dd($date->diffInDays($now));
$loggedUser->exchange_keys_last_time = 2018-04-04 00:00:00.000000 and $now = 2018-04-02 15:16:18.902924 and I'm getting this weird result saying that the diffInDays() = 1 which in my mind doesn't make sense since these dates are two days apart.
Any suggestion to get if $date is older than 1 day comparing to $now?
If you're not concerned about anything smaller than a second (it seems you're not), you can simply compare the difference in seconds against a known value (seconds in a day).
$secondsInDay = 86400; // 3600 * 24
$expired = $date->diffInSeconds($now) > $secondsInDay;
Do note that this probably won't work with DST change and you should look into other solutions if that's a concern for you.
I need to detect when a timestamp is in daylight saving or not.
I'm using this code to test the functionality:
<?php
date_default_timezone_set('Europe/Berlin');
$timestamp = $baseTimestamp = 1509234900; // Sunday, 29 October of 2017 1:55:00 GMT+02:00 DST
$date = (new DateTime)->setTimestamp($baseTimestamp);
echo "DateTime\t\t| Is in summer \t| Minutes passed\n";
for($i = 0; $i < 70; $i++) {
$date = (new DateTime)->setTimestamp($timestamp);
echo $date->format("Y-m-d H:i:s \t|I") . "\t\t| " . ($timestamp - $baseTimestamp)/60 . "\n";
$timestamp = $timestamp + 60;
}
https://3v4l.org/dqNlK
Working with Europe/Berlin, I've seen that in March, when at 2.00 we pass from winter to summer, php solves it right, but then in October, when it is supposed to come back from summer to winter at 3.00, it doesn't work as expected.
In this case, we have two timestamps corresponding to the same hour (at 3 is 2 again), but the timestamp is unique, so for 2.00 there must be one timestamp in the summer time and another one in the winter time.
Using hhvm, it shows the right value, but normal php interpreters show that is not in summer for both 2.00 (the first one, which is 2am and the second one which is when at 3am is 2am again. This is the one that should say is not in summer anymore)
Yes, there are several long-lived, unresolved, DST-related bugs in PHP.
You appear to have hit on this one:
https://bugs.php.net/bug.php?id=68549
function isSummer($timestamp) {
$date = (new DateTime)->setTimestamp($timestamp);
if ($date->format('I') == 1) {
return true;
}
return ($date->getTimestamp() > $timestamp);
}
I think this is going to do the trick
i my php codes i do time()-86400 to fetch everything from the last 24 hours, but how i can get everything today or everything from yesterday. thus it is no longer 86400 seconds, it should be after 12 midnight till current time.
hope this makes sense.. but how i can do this?
If you are "fetching" from a database, why not do it in the query?
SELECT * FROM `table` WHERE DATE(`created_at`) = '2011-03-28';
If you are storing the date as a unix timestamp:
SELECT * FROM `table` WHERE DATE(FROM_UNIXTIME(`created_at`)) = '2011-03-28';
time()-strtotime('today') - difference between now and midnight; time()-strtotime('yesterday') - difference between now and yesterday midnight; time()-strtotime('-2 days')...
for yesterday only (range $min to $max)
$start = strtotime('yesterday')
$end = strtotime('today') - 1;
etc.
Following will give you the seconds passed since January 1, 1970. Every object with a timestamp higher than this value is from the current day (given that you have set your timezones and local time correctly).
$time = strtotime(date('Y-m-d 00:00:00'));
You can use the PHP date and strtotime function in order to pick a day from now and retrieve the seconds that specific date. For more info, see: http://php.net/manual/en/function.date.php and http://php.net/manual/en/function.strtotime.php
I agree with Gordon here - there are so many date/time examples. But hey, let's go over it again - assuming today begins at midnight, you use:
$start = strtotime('today');
Assuming "today" ends at 23:59, simple arithmetics imply that if you increment the $start by 24 hours and take away 1 second - you'll reach the end of today.
So:
$start = strtotime('today');
$end = $start + (3600 * 24) - 1;
I need to create functions in PHP that let me step up/down given datetime units. Specifically, I need to be able to move to the next/previous month from the current one.
I thought I could do this using DateTime::add/sub(P1M). However, when trying to get the previous month, it messes up if the date value = 31- looks like it's actually trying to count back 30 days instead of decrementing the month value!:
$prevMonth = new DateTime('2010-12-31');
Try to decrement the month:
$prevMonth->sub(new DateInterval('P1M')); // = '2010-12-01'
$prevMonth->add(DateInterval::createFromDateString('-1 month')); // = '2010-12-01'
$prevMonth->sub(DateInterval::createFromDateString('+1 month')); // = '2010-12-01'
$prevMonth->add(DateInterval::createFromDateString('previous month')); // = '2010-12-01'
This certainly seems like the wrong behavior. Anyone have any insight?
Thanks-
NOTE: PHP version 5.3.3
(Credit actually belongs to Alex for pointing this out in the comments)
The problem is not a PHP one but a GNU one, as outlined here:
Relative items in date strings
The key here is differentiating between the concept of 'this date last month', which, because months are 'fuzzy units' with different numbers of dates, is impossible to define for a date like Dec 31 (because Nov 31 doesn't exist), and the concept of 'last month, irrespective of date'.
If all we're interested in is the previous month, the only way to gaurantee a proper DateInterval calculation is to reset the date value to the 1st, or some other number that every month will have.
What really strikes me is how undocumented this issue is, in PHP and elsewhere- considering how much date-dependent software it's probably affecting.
Here's a safe way to handle it:
/*
Handles month/year increment calculations in a safe way,
avoiding the pitfall of 'fuzzy' month units.
Returns a DateTime object with incremented month/year values, and a date value == 1.
*/
function incrementDate($startDate, $monthIncrement = 0, $yearIncrement = 0) {
$startingTimeStamp = $startDate->getTimestamp();
// Get the month value of the given date:
$monthString = date('Y-m', $startingTimeStamp);
// Create a date string corresponding to the 1st of the give month,
// making it safe for monthly/yearly calculations:
$safeDateString = "first day of $monthString";
// Increment date by given month/year increments:
$incrementedDateString = "$safeDateString $monthIncrement month $yearIncrement year";
$newTimeStamp = strtotime($incrementedDateString);
$newDate = DateTime::createFromFormat('U', $newTimeStamp);
return $newDate;
}
Easiest way to achieve this in my opinion is using mktime.
Like this:
$date = mktime(0,0,0,date('m')-1,date('d'),date('Y'));
echo date('d-m-Y', $date);
Greetz Michael
p.s mktime documentation can be found here: http://nl2.php.net/mktime
You could go old school on it and just use the date and strtotime functions.
$date = '2010-12-31';
$monthOnly = date('Y-m', strtotime($date));
$previousMonth = date('Y-m-d', strtotime($monthOnly . ' -1 month'));
(This maybe should be a comment but it's to long for one)
Here is how it works on windows 7 Apache 2.2.15 with PHP 5.3.3:
<?php $dt = new DateTime('2010-12-31');
$dt->sub(new DateInterval('P1M'));
print $dt->format('Y-m-d').'<br>';
$dt->add(DateInterval::createFromDateString('-1 month'));
print $dt->format('Y-m-d').'<br>';
$dt->sub(DateInterval::createFromDateString('+1 month'));
print $dt->format('Y-m-d').'<br>';
$dt->add(DateInterval::createFromDateString('previous month'));
print $dt->format('Y-m-d').'<br>'; ?>
2010-12-01
2010-11-01
2010-10-01
2010-09-01
So this does seem to confirm it's related to the GNU above.
Note: IMO the code below works as expected.
$dt->sub(new DateInterval('P1M'));
Current month: 12
Last month: 11
Number of Days in 12th month: 31
Number of Days in 11th month: 30
Dec 31st - 31 days = Nov 31st
Nov 31st = Nov 1 + 31 Days = 1st of Dec (30+1)
I have a simple situation where I have a user supplied week number X, and I need to find out that week's monday's date (e.g. 12 December). How would I achieve this? I know year and week.
Some code based mainly on previous proposals:
$predefinedYear = 2009;
$predefinedWeeks = 47;
// find first mоnday of the year
$firstMon = strtotime("mon jan {$predefinedYear}");
// calculate how much weeks to add
$weeksOffset = $predefinedWeeks - date('W', $firstMon);
// calculate searched monday
$searchedMon = strtotime("+{$weeksOffset} week " . date('Y-m-d', $firstMon));
An idea to get you started:
take first day of year
add 7 * X days
use strtodate, passing in "last Monday" and the date calculated above.
May need to add one day to the above.
Depending on the way you are calculating week numbers and the start of the week this may sometimes be out. (i.e. if the monday in the first week of the year was actually in the previous year!)
TEST THIS THOROUGHLY - but I've used a similar approach for similar calcualtions in the past.
This will solve the problem for you. It mainly derives from Mihail Dimitrov's answer, but simplifies and condenses this somewhat. It can be a one-line solution if you really want it to be.
function getMondaysDate($year, $week) {
if (!is_numeric($year) || !is_numeric($week)) {
return null;
// or throw Exception, etc.
}
$timestamp = strtotime("+$week weeks Monday January $year");
$prettyDate = date('d M Y');
return $prettyDate;
}
A couple of notes:
As above, strtotime("Monday January $year") will give you the timestamp of the first Monday of the year.
As above +X weeks will increment a specified date by that many weeks.
You can validate this by trying:
date('c',strtotime('Sunday Jan 2018'));
// "2018-01-07T00:00:00+11:00" (or whatever your timezone is)
date('c',strtotime('+1 weeks Sunday Jan 2018'));
// "2018-01-14T00:00:00+11:00" (or whatever your timezone is)
date('c',strtotime('+52 weeks Sunday Jan 2018'));
// "2019-01-06T00:00:00+11:00"
Due to reputation restriction i can't post multiple links
for details check
http://php.net/manual/en/function.date.php and http://php.net/manual/en/function.mktime.php
you can use something like this :
use mktime to get a timestamp of the week : $stamp = mktime(0,0,0,0,<7*x>,) {used something similar a few years back, so i'm not sure it works like this}
and then use $wDay = date('N',$stamp). You now have the day of the week, the timestamp of the monday should be
mktime(0,0,0,0,<7*x>-$wDay+1,) {the 'N' parameter returns 1 for monday, 6 for sunday}
hope this helps
//To calculate 12 th Monday from this Monday(2014-04-07)
$n_monday=12;
$cur_mon=strtotime("next Monday");
for($i=1;$i<=$n_monday;$i++){
echo date('Y-m-d', $cur_mon);
$cur_mon=strtotime(date('Y-m-d', strtotime("next Monday",$cur_mon)));
}
Out Put
2014-04-07
2014-04-14
2014-04-21
2014-04-28
2014-05-05
2014-05-12
2014-05-19
2014-05-26
2014-06-02
2014-06-09
2014-06-16
2014-06-23