How to get the UNIX timestamp range of the current hour, i mean one of the first second and the other for the last second. so if it's 18:45 i would get the timestamp of 18:00 and 18:59.
Thanks
You can get the components of the current time with getdate(), and use mktime() to find the timestamps:
$date = getdate();
$start = mktime($date['hours'], 0, 0);
$end = $start + (60*60);
You can also use date(), which is slightly simpler:
$start = mktime(date("H"), 0, 0);
$end = $start + (60*60);
$start = mktime(date('H'), 0, 0);
$end = mktime(date('H'), 59, 59);
Could be generalized for any timestamp, not just the current time, as:
$time = time(); // some timestamp
$start = mktime(date('H', $time), 0, 0, date('n', $time), date('j', $time), date('Y', $time));
$end = mktime(date('H', $time), 59, 59, date('n', $time), date('j', $time), date('Y', $time));
Related
For example
02-11-2018 03:00pm - 05-11-2018 11:00am should be 2hrs.
Because 3rd and 4th are weekends.
$date1 = "2018-03-01 11:12:45";
$date2 = "2018-03-04 15:37:04";
$date1Timestamp = strtotime($date1);
$date2Timestamp = strtotime($date2);
$difference = $date2Timestamp - $date1Timestamp;
echo $difference;
You can use mktime() to create UNIX timestamps for the two date/times you want to compare. These timestamps will represent the number of seconds between the Unix Epoch (January 1 1970 00:00:00 GMT) and the time specified. Since they will both be in seconds, it makes it very easy to calculate the seconds between the two timestamps:
<?php
//set start time and end time - mktime(hour, minute, second, month, day, year)
$startTime = mktime(15, 0, 0, 11, 2, 2018); // 2-11-2018 3:00PM
$endTime = mktime(11, 0, 0, 11, 5, 2018); // 5-11-2018 11:00AM
//calculate total number of seconds between two date/times
$totalSeconds = $endTime - $startTime;
//apply whatever other math you need...
?>
As far as accounting for weekends and business hours, you will need to get creative with determining how many weekend days exist between the two date/times and what hours fall within business hours on business days. The PHP manual for date functions will come in handy. The following code produces the results you are looking for:
<?php
//set business start and end hours
$businessStartHour = 10; //10 AM
$businessEndHour = 16; //4 PM
//set weekend days
$arrWeekendDays = array(6,0); //numeric representations of Saturday (6) and Sunday (0)
//set start and end dates and times
//2-11-2018 3 PM
$startHour = 15;
$startMinute = 0;
$startSecond = 0;
$startMonth = 11;
$startDay = 2;
$startYear = 2018;
//5-11-2018 11 AM
$endHour = 11;
$endMinute = 0;
$endSecond = 0;
$endMonth = 11;
$endDay = 5;
$endYear = 2018;
//create UNIX timestamps
$startTime = mktime($startHour, $startMinute, $startSecond, $startMonth, $startDay, $startYear);
$endTime = mktime($endHour, $endMinute, $endSecond, $endMonth, $endDay, $endYear);
//ensure $endTime is greater than $startTime
if($startTime >= $endTime){
//invalid start and end datetimes
die("Invalid start and end datetimes.");
}
//calculate eligible seconds from partial time on first and last day
$totalSeconds = 0;
$currentTime = mktime(0, 0, 0, $startMonth, $startDay, $startYear); //beginning of $startTime day
$lastFullDay = mktime(0, 0, 0, $endMonth, $endDay, $endYear); //beginning of $endTime day
$startingBusinessTime = mktime($businessStartHour, 0, 0, $startMonth, $startDay, $startYear);
$endingBusinessTime = mktime($businessEndHour, 0, 0, $endMonth, $endDay, $endYear);
if($startTime < $startingBusinessTime){
$startTime = $startingBusinessTime;
}
if($endTime > $endingBusinessTime){
$endTime = $endingBusinessTime;
}
if($currentTime == $lastFullDay){
//$startTime and $endTime occur on the same day
if($endTime > $startTime){
$totalSeconds += ($endTime - $startTime);
}
}else{
//$startTime and $endTime do not occur on the same day
$startingBusinessTime = mktime($businessStartHour, 0, 0, $endMonth, $endDay, $endYear);
$endingBusinessTime = mktime($businessEndHour, 0, 0, $startMonth, $startDay, $startYear);
if($endingBusinessTime > $startTime){
$totalSeconds += ($endingBusinessTime - $startTime);
}
if($endTime > $startingBusinessTime){
$totalSeconds += ($endTime - $startingBusinessTime);
}
}
//calculate eligible seconds from all full days in between start day and end day
$fullDayBusinessSeconds = (($businessEndHour - $businessStartHour) * 3600);
//set $currentTime to beginning of first full day
$nextDay = $currentTime + (26 * 3600); //add 26 hours to $currentTime to get into the next day, compensating for possible daylight savings
$currentTime = mktime(0, 0, 0, date('n', $nextDay), date('j', $nextDay), date('Y', $nextDay));
while($currentTime < $lastFullDay){
//determine if $currentTime is a weekday
if(!in_array(date('w', $currentTime), $arrWeekendDays)){
//it's a business day, add all business seconds to $totalSeconds
$totalSeconds += $fullDayBusinessSeconds;
}
//increment $currentTime to beginning of next day
$nextDay = $currentTime + (26 * 3600); //add 26 hours to $currentTime to get into the next day, compensating for possible daylight savings
$currentTime = mktime(0, 0, 0, date('n', $nextDay), date('j', $nextDay), date('Y', $nextDay));
}
echo "Total eligible time between start time and end time: " . $totalSeconds . " seconds (" . convertSecToTime($totalSeconds) . ")";
function convertSecToTime($sec)
{
$date1 = new DateTime("#0");
$date2 = new DateTime("#$sec");
$interval = date_diff($date1, $date2);
return $interval->format('%y Years, %m months, %d days, %h hours, %i minutes and %s seconds');
// convert into Days, Hours, Minutes
// return $interval->format('%a days, %h hours, %i minutes and %s seconds');
}
?>
Kindly have a look at this precise php function returning days count with weekends excluded.
$start= "2018-03-01 11:12:45";
$end= "2018-04-01 15:37:04";
echo Count_Days_Without_Weekends($start, $end);
function Count_Days_Without_Weekends($start, $end){
$days_diff = floor(((abs(strtotime($end) - strtotime($start))) / (60*60*24)));
$run_days=0;
for($i=0; $i<=$days_diff; $i++){
$newdays = $i-$days_diff;
$futuredate = strtotime("$newdays days");
$mydate = date("F d, Y", $futuredate);
$today = date("D", strtotime($mydate));
if(($today != "Sat") && ($today != "Sun")){
$run_days++;
}
}
return $run_days;
}
Try it out, it really works..
I am Using Bellow Script. but it give me Result but not According To My Requirement.
This is the Week number i need. Week Calendar
$month = "10";
$year = "2016";
$beg = (int) date('W', strtotime("first monday of $year-$month"));
$end = (int) date('W', strtotime("last monday of $year-$month"));
print(join(', ', range($beg, $end)));
above code Gives Result. 40, 41, 42, 43, 44
With PHP >= 5.3 do
$month = "10";
$year = "2016";
$beg = (int) date('W', strtotime("first day of $year-$month"));
$end = (int) date('W', strtotime("last day of $year-$month"));
print(join(', ', range($beg, $end)));
here is my code (using laravel)
$start = '05-01-2016';
$end = '05-03-2016';
$start_date = new Carbon;
$end_date = new Carbon;
$format = 'm-d-Y';
$begin = Carbon::createFromFormat($format, $start);
$begin->setTime(0, 0, 0);
$end = Carbon::createFromFormat($format, $end);
$end->setTime(59, 59, 59);
//dd($begin,$end);
$interval = new \DateInterval('P1D');
$dateRange = new \DatePeriod($begin, $interval, $end);
foreach ($dateRange as $date) {
$start_time = $start_date->setDateTime($date->format("Y"), $date->format("m"), $date->format("d"), 0, 0, 0)->toDateTimeString();
$end_time =$end_date->setDateTime($date->format("Y"), $date->format("m"), $date->format("d"), 23, 59, 59)->toDateTimeString();
var_dump($start_time);
//var_dump($end_time);
}
expected output would be (atleast for me)
05-01-2016
05-02-2016
it actually gives me
05-01-2016
05-02-2016
05-03-2016
05-04-2016
05-05-2016
I cant understand it... any help is appreciated
here is output
You set 59 hour :) - It is more than two days. Now your end datetime is Thu, 05 May 2016 11:59:59
$end->setTime(59, 59, 59);
Set 23 hours and it will work
$end->setTime(23, 59, 59);
I have an action which accepts a year and an optional month. I need to query all articles written within that time, so I need the absolute first and last valid datetime for that timespan.
$start = new \DateTime();
$start->setDate((int) $year, (int) ($month ?: 1), 1);
$start->setTime(0, 0);
$end = clone $start;
$end->add(new \DateInterval($month ? 'P1M' : 'P1Y'));
$end->sub(new \DateInterval('PT1S'));
Is there a cleaner way to write this?
$start = mktime(0, 0, 0, $month ?: 1, 1, $year);
$end = mktime(23, 59, 59, $month ?: 12, $month ? date('t', $start) : 31, $year);
or
$start = new \DateTime("$year-" . ($month ?: 1) . '-1 00:00:00');
$end = new \DateTime("$year-" . ($month ?: 12) . '-' . ($month ? $start->format('t') : 31) . ' 23:59:59');
Not sure if you'd consider this cleaner, but it's shorter and does without relative calculations.
The cleanest and most understandable way to write this is probably:
if ($month) {
$start = new \DateTime("$year-$month-1 00:00:00");
$end = new \DateTime("$year-$month-" . $start->format('t') . ' 23:59:59');
} else {
$start = new \DateTime("$year-1-1 00:00:00");
$end = new \DateTime("$year-12-31 23:59:59");
}
You might not need to involve DateTime much at all here if you're going to use this as value for an SQL query.
How can one get the timestamps of the first and last minutes of any month using PHP?
You can use mktime and date:
$first_minute = mktime(0, 0, 0, date("n"), 1);
$last_minute = mktime(23, 59, 59, date("n"), date("t"));
That is for the current month. If you want to have it for any month, you have change the month and day parameter accordingly.
If you want to generate it for every month, you can just loop:
$times = array();
for($month = 1; $month <= 12; $month++) {
$first_minute = mktime(0, 0, 0, $month, 1);
$last_minute = mktime(23, 59, 59, $month, date('t', $first_minute));
$times[$month] = array($first_minute, $last_minute);
}
DEMO
With PHP 5.3, you can do
$oFirst = new DateTime('first day of this month');
$oLast = new DateTime('last day of this month');
$oLast->setTime(23, 59, 59);
In PHP 5.2
Note: as AllThecode pointed out in the comments below, this next example only works if you do the $oFirst portion first. If you add +1 month to new DateTime the result will jump an extra month ahead on the last day of the month (as of php 5.5.9).
$oToday = new DateTime();
$iTime = mktime(0, 0, 0, $oToday->format('m'), 1, $oToday->format('Y'));
$oFirst = new DateTime(date('r', $iTime));
$oLast = clone $oFirst;
$oLast->modify('+1 month');
$oLast->modify('-1 day');
$oLast->setTime(23, 59, 59);
Use mktime for generating timestamps from hour/month/day/... values and cal_days_in_month to get the number of days in a month:
$month = 1; $year = 2011;
$firstMinute = mktime(0, 0, 0, $month, 1, $year);
$days = cal_days_in_month(CAL_GREGORIAN, $month, $year);
$lastMinute = mktime(23, 59, 0, $month, $days, $year);
I think better then
$first_minute = mktime(0, 0, 0, date("n"), 1);
$last_minute = mktime(23, 59, 0, date("n"), date("t"));
is:
$first_minute = mktime(0, 0, 0, date("n"), 1);
$last_minute = mktime(23, 59, 0, date("n") + 1, 0);
This requires PHP > 5.2 and need adjustement for the "minutes" part
$year = ...; // this is your year
$month = ...; // this is your month
$month = ($month < 10 ? '0' . $month : $month);
$start = new DateTime($year . '-' . $month . '-01 00:00:00');
$end = $start->modify('+1 month -1 day -1 minute'); //perhaps this need 3 "->modify"
echo $start->format('U');
echo $end->format('U');
(not tested)
Ref: http://www.php.net/manual/en/class.datetime.php
$date = new \DateTime('now');//Current time
$date->modify("-1 month");//get last month
$startDate = $date->format('Y-m-01');
$endDate = $date->format('Y-m-t');
Best Way do like this..
$first_day = date('m-01-Y h:i:s',strtotime("-1 months"));
$last_day = date('m-t-Y h:i:s',strtotime("-1 months"));