Specific UNIX Timestamps from DateTime in PHP - php

So, here's the deal. I've been banging my head off of this for the past couple of hours and really haven't made any headway. I've ready through several of these, and even tried uncle google, but no joy.
I have a project I'm working on that deals with a lot of nightclubs and after-hours locations. As a result, we are redefining the day to be from 5:00am-4:59am. I'm having a heck of a time getting those start/end times from the current time. It must be time-zone specific is the part that is screwing me up.
This is ugly, this is after several different failed theories...I'm really chasing my own tail on this one, so any help would be appreciated.
function util_TimeInfo($timezone, $dst){
// Get current DateTime
$dt = new DateTime();
$tz = new DateTimeZone($timezone);
$dt->setTimezone($tz);
// split to variables
$year = $dt->format('Y');
$month = $dt->format('m');
$day = $dt->format('d');
$hour = $dt->format('H');
$minute = $dt->format('i');
$second = $dt->format('s');
// Convert hour to string
$inthour = intval($hr);
// Check which day it is a part of
$mytime[0] = time();
if($inthour < 5){
$start_d = date('d', strtotime('-1 day', $mytime[0]));
$start_m = date('m', strtotime('-1 day', $mytime[0]));
$start_y = date('Y', strtotime('-1 day', $mytime[0]));
$end_d = date('d', $mytime[0]);
$end_m = date('m', $mytime[0]);
$end_y = date('Y', $mytime[0]);
} else{
$start_d = date('d', $mytime[0]);
$start_m = date('m', $mytime[0]);
$start_y = date('Y', $mytime[0]);
$end_d = date('d', strtotime('+1 day', $mytime[0]));
$end_m = date('m', strtotime('+1 day', $mytime[0]));
$end_y = date('Y', strtotime('+1 day', $mytime[0]));
}
// Create current start of day and end of day in unix timestamp
$mytime[1] = mktime('05', '00', '00', $start_m, $start_d, $start_y, $dst);
$mytime[2] = mktime('04', '59', '59', $end_m, $end_d, $end_y, $dst);
//Return times
return $mytime;
}

Using Glavic's code as a base, I was able to get it working how I wanted with an if statement to handle the time between midnight and 5am.
// Get current DateTime
$dt = new DateTime();
$tz = new DateTimeZone($timezone);
$dt->setTimezone($tz);
// Set cutoff for 5am
$cutoff = new DateTime('today 5:00am', $tz);
// Adjust start/end for day
if($dt < $cutoff){
$start = new DateTime('yesterday 5:00:00am', $tz);
$end = new DateTime('today 4:59:59am', $tz);
} else{
$start = new DateTime('today 5:00:00am', $tz);
$end = new DateTime('tomorrow 4:59:59am', $tz);
}

What about this simple code:
$tz = new DateTimezone('Europe/Berlin');
$now = new DateTime('now', $tz);
$start = new DateTime('today 5:00am', $tz);
$end = new DateTime('tomorrow 4:59am', $tz);
if ($now < $start) {
$start = new DateTime('yesterday 5:00am', $tz);
$end = new DateTime('today 4:59am', $tz);
}
demo

Related

how to check if two datetime between current times

i wanna check if current time is between current day 8AM and next day 2AM
i did try
$currentTime = date('h:i A', time());
$startTime = "8:00 AM";
$endTime = "2:49 AM";
if ((strtotime($currentTime) >= strtotime($startTime)) && (strtotime($currentTime) <= strtotime($endTime))) {
// do something
}
what should result
true
but its return
false
If dates are part of your logic, then use them. You can utilize DateTime's relative formats:
$start = new DateTime('today 08:00 AM');
$end = new DateTime('tomorrow 02:00 AM');
$current = new DateTime();
if ($start <= $current && $current <= $end) {
// do something
}
I updated your code a bit and it working
$currentTime = date('h:i A'); //UTC time
$startTime = "8:00 AM";
$endTime = "11:50 PM";
if ((strtotime($currentTime) >= strtotime($startTime)) && (strtotime($currentTime) <= strtotime($endTime))) {
print 'test';
}

Get whole week date starting from sunday to saturday from given date

Hello guys i am working in php and my requirement is to get complete week dates from given date as i need to calculate weekly working hour. And week must be started from sunday to saturday not monday to sunday. I have code which works properly for other days of week except sunday. it means if give any dates from monday to saturday it works properly but if i give sunday's date it give last week's dates. please check my code and advise me for better solution.
$days = array();
$ddate = "2018-01-07";
$date = new DateTime($ddate);
$week = $date->format("W");
$y = date("Y", strtotime($ddate));
echo "Weeknummer: $week"."<br>";
echo "Year: $y"."<br>";
for($day=0; $day<=6; $day++)
{
$days[$day] = date('Y-m-d', strtotime($y."W".$week.$day))."<br>";
}
print_r($days);
Using the DateTime, DateInterval and DatePeriod classes you could do it like this perhaps
function getperiod( $start ){
return new DatePeriod(
new DateTime( $start ),
new DateInterval('P1D'),
new DateTime( date( DATE_COOKIE, strtotime( $start . '+ 7days' ) ) )
);
}
$start='2018-01-07';
$period=getperiod( $start );
foreach( $period as $date ){
echo $date->format('l -> Y-m-d') . '<br />';
}
Which returns
Sunday -> 2018-01-07
Monday -> 2018-01-08
Tuesday -> 2018-01-09
Wednesday -> 2018-01-10
Thursday -> 2018-01-11
Friday -> 2018-01-12
Saturday -> 2018-01-13
Or, by modifying the parameters of the getperiod function you can make that function far more flexible.
function getperiod( $start, $interval='P1D', $days=7 ){
return new DatePeriod(
new DateTime( $start ),
new DateInterval( $interval ),
new DateTime( date( DATE_COOKIE, strtotime( $start . '+ '.$days.' days' ) ) )
);
}
$start='2018-01-07';
$days=array();
$period=getperiod( $start );
foreach( $period as $date ){
$days[]=$date->format('Y-m-d');
}
echo '<pre>',print_r($days,true),'</pre>';
For instance: To find every Sunday for the next year
$period=getperiod( $start,'P7D', 365 );
foreach( $period as $date ){
$days[]=$date->format('Y-m-d');
}
echo '<pre>',print_r($days,true),'</pre>';
To ensure that the calculations begin on a Sunday which has a numeric value of 7
function getperiod( $start, $interval='P1D', $days=7 ){
return new DatePeriod(
new DateTime( $start ),
new DateInterval( $interval ),
new DateTime( date( DATE_COOKIE, strtotime( $start . '+ '.$days.' days' ) ) )
);
}
/* A date from which to begin calculations */
$start='2018-01-01';
/* Array to store output */
$days=array();
/* integer to represent which day of the week to operate upon */
$startday = 7;
/* Output format for resultant dates */
$output='Y-m-d';
/* Calculate initial startdate given above variables */
$start=date( DATE_COOKIE, strtotime( $start . ' + ' . ( $startday - date( 'N', strtotime( $start ) ) ) . ' days' ) );
/* Get the period range */
$period=getperiod( $start );
foreach( $period as $date ){
/* store output in desired format */
$days[]=$date->format( $output );
}
/* do something with data */
echo '<pre>',print_r($days,true),'</pre>';
From source,
Here is the snippet you are looking for,
// set current date
$date = '01/03/2018';
// parse about any English textual datetime description into a Unix timestamp
$ts = strtotime($date);
// calculate the number of days since Monday
$dow = date('w', $ts);
$offset = $dow - 1;
if ($offset < 0) {
$offset = 6;
}
// calculate timestamp for the Monday
$ts = $ts - $offset*86400;
// loop from Monday till Sunday
for ($i = 0; $i < 7; $i++, $ts += 86400){
print date("m/d/Y l", $ts) . "\n";
}
Here is working demo.
If you need normal standard format code,
Here is your snippet,
// set current date
$date = '2018-01-03';
// parse about any English textual datetime description into a Unix timestamp
$ts = strtotime($date);
// calculate the number of days since Monday
$dow = date('w', $ts);
$offset = $dow - 1;
if ($offset < 0) {
$offset = 6;
}
// calculate timestamp for the Monday
$ts = $ts - $offset * 86400;
// loop from Monday till Sunday
for ($i = 0; $i < 7; $i++, $ts += 86400) {
print date("Y-m-d l", $ts) . "\n";
}
Here is working demo.
EDIT
As per your requirement, now week will start from sunday to saturday
<?php
// set current date
$date = '2018-01-03';
// parse about any English textual datetime description into a Unix timestamp
$ts = strtotime($date);
// calculate the number of days since Sunday
$dow = date('w', $ts);
$offset = $dow;
if ($offset < 0) {
$offset = 6;
}
// calculate timestamp for the Sunday
$ts = $ts - $offset * 86400;
// loop from Sunday till Saturday
for ($i = 0; $i < 7; $i++, $ts += 86400) {
print date("Y-m-d l", $ts) . "\n";
}
<?php
$days = array();
$ddate = "2018-01-07";
$y = date("Y", strtotime($ddate));
if(date("l", strtotime($ddate))=='Sunday'){
$ddate = date("Y-m-d ", strtotime($ddate. "+1 day"));
}
$date = new DateTime($ddate);
$week = $date->format("W");
echo "<br/>";
echo "Weeknummer: $week"."<br>";
echo "Year: $y"."<br>";
for($day=0; $day<=6; $day++)
{
$days[$day] = date('Y-m-d', strtotime($y."W".$week.$day))."<br>";
}
print_r($days);
?>
try this:
$days = array();
$ddate = "2018-01-07";
$date = new DateTime($ddate);
$week = $date->format("N")==7?$date->modify("+1 week")->format("W"):$date->format("W");
$y = date("Y", strtotime($ddate));
echo "Weeknummer: $week"."<br>";
echo "Year: $y"."<br>";
for($day=0; $day<=6; $day++)
{
$days[$day] = date('Y-m-d', strtotime($y."W".$week.$day))."<br>";
}
print_r($days);
$dto = new DateTime();
$year = date_create($this->week_date)->format('o');
$week_no = date('W', strtotime($this->week_date));
$dto->setISODate($year, $week_no);
$dto->modify('-1 days');
$ret['sunday'] = $dto->format('Y-m-d');
$dto->modify('+1 days');
$ret['monday'] = $dto->format('Y-m-d');
$dto->modify('+1 days');
$ret['tuesday'] = $dto->format('Y-m-d');
$dto->modify('+1 days');
$ret['wednesday'] = $dto->format('Y-m-d');
$dto->modify('+1 days');
$ret['thursday'] = $dto->format('Y-m-d');
$dto->modify('+1 days');
$ret['friday'] = $dto->format('Y-m-d');
$dto->modify('+1 days');
$ret['saturday'] = $dto->format('Y-m-d');
$dto->modify('+1 days');
$ret['next_sunday'] = $dto->format('Y-m-d');

Print months between -6 and +6 months

I'm trying to echo months from 1 year range, like example date 02-2016
I want months between (02-2016 - 6months) and (02-2016 + 6 months)
$now = strtotime(date('d-m-Y'));
$start = strtotime('-6 months');
$end = strtotime('+6 months');
while($start < $end) {
$links .= "".date('F', $start)."";
$start = strtotime($start+'1 month');
}
when echoing $links, I just get "August" echoed.
Define your start date and end date as below:-
$start = $month =strtotime("-6 months", strtotime('20015-02-01'));
$end = strtotime("+6 months", strtotime('20015-02-01'));
while($month < $end)
{
echo date('F Y', $month), PHP_EOL;
$month = strtotime("+1 month", $month);
}
Hope it will help you :)
Try:
$now = strtotime(date('d-m-Y'));
$start = strtotime('-6 months');
$end = strtotime('+6 months');
$links = "";
while($start < $end) {
$links .= "".date('F', $start)."";
$start = strtotime('+1 month', $start);
}
for strtotime the reference point is the second parameter: http://php.net/strtotime

Get month name using start date and end date?

$startDate = "2014-03-01";
$endDate= "2014-05-25";
Result required: March, April, May;
for that PHP delivers the DatePeriod object. Just have a look at the following example.
$period = new DatePeriod(
new DateTime('2014-03-01'),
DateInterval::createFromDateString('1 month'),
new DateTime('2014-05-25')
);
foreach ($period as $month) {
echo strftime('%B', $month->format('U'));
}
A quick solution is to parse each day and check it month:
$startDate = "2014-03-01";
$endDate = "2014-05-25";
$start = strtotime($startDate);
$end = strtotime($endDate);
$result = array();
while ( $start <= $end )
{
$month = date("M", $start);
if( !in_array($month, $result) )
$result[] = $month;
$start += 86400;
}
print_r($result);
I believe it can be done much efficient by new OOP (DateTime object) approach, but this is fast and no-brain if you need to make it work.
<?php
$startDate = "2014-03-01";
echo date('F',strtotime($startDate));
?
$date = date('F',strtotime($startDate));
For full month representation (ie Januaray, February, etc)
$date = date('M',strtotime($startDate));
For abbreviated...(ie Jan, Feb, Mar)
REFERENCE
If you wanna echo out those months in between based on two dates....
$d = "2014-03-01";
$startDate = new DateTime($d);
$endDate = new DateTime("2014-05-01");
function diffInMonths(DateTime $date1, DateTime $date2)
{
$diff = $date1->diff($date2);
$months = $diff->y * 12 + $diff->m + $diff->d / 30;
return (int) round($months);
}
$t = diffInMonths($startDate, $endDate);
for($i=0;$i<$t+1;$i++){
echo date('F',strtotime($d. '+'.$i.' Months'));
}
PHP SANDBOX EXAMPLE

PHP - Get start and end date of current date interval

I have as unix timestamps
$now = strtotime("2013-12-10");
$start_date = strtotime("2013-01-01");
$end_date = strtotime("2013-12-31");
The $start date and $end date span a period of time and the $now timestamp sits in the middle of the two.
I also have a variable date interval like so:
$interval = new DateInterval('P1W');
// or
$interval = new DateInterval('P3D');
Given the above how do I get the start and end timestamps of the interval that now sits in?
The $now, $start_date, $end_date and the interval will be dynamic.
Example
Lets say I have these parameters:
$start_date = '2013-01-01 00:00:00';
$end_date = '2013-12-31 23:59:59';
$now = '2013-12-10 15:45:34';
$interval = new DateInterval( 'P1W' );
I want to know the start and end date of the interval $now sits in. The output I would expect from the above params is:
$int_start_date = '2013-12-10 00:00:00';
$int_end_date = '2013-12-16 23:59:59';
I think this is a less hacky and cleaner approach than yours.
$start_date = new DateTime( '2013-01-01 00:00:00' );
$end_date = new DateTime( '2013-12-31 23:59:59' );
$end_date_ts = $end_date->getTimestamp();
$now = new DateTime( '2013-12-10 15:45:34' );
$now_ts = $now->getTimestamp();
$interval = new DateInterval( 'P1W' );
$periods = new DatePeriod( $start_date, $interval, $end_date );
/** #var \DateTime $period */
foreach($periods as $period){
$periodEnd = clone $period;
$periodEnd->add($interval);
if($period < $now && $now < $periodEnd){
$result = iterator_to_array(new \DatePeriod($period, $interval, $periodEnd->add($interval)));
$int_start_date = $result[0];
$int_end_date = $result[1];
break;
}
}
/** #var DateTime $int_start_date */
/** #var DateTime $int_end_date */
var_dump( $int_start_date->format( 'Y-m-d H:i:s' ) );
var_dump( $int_end_date->modify( '-1 Second' )->format( 'Y-m-d H:i:s' ) );
I have figured the problem myself however is hacky
$start_date = new DateTime( '2013-01-01 00:00:00' );
$end_date = new DateTime( '2013-12-31 23:59:59' );
$end_date_ts = $end_date->getTimestamp();
$now = new DateTime( '2013-12-10 15:45:34' );
$now_ts = $now->getTimestamp();
$interval = new DateInterval( 'P1W' );
$period = new DatePeriod( $start_date, $interval, $end_date );
$intervals = array();
foreach ( $period as $dt ) {
$intervals[] = $dt->getTimestamp();
}
$intervals[] = $end_date_ts;
$int_start_date = new DateTime();
$int_end_date = new DateTime();
for ( $i = 0; $i < count( $intervals ); $i++ ) {
if ( $now_ts >= $intervals[$i] && $now_ts <= $intervals[$i+1]) {
$int_start_date->setTimestamp($intervals[$i]);
$int_end_date->setTimestamp($intervals[$i+1]-1);
break;
}
}
var_dump( $int_start_date->format( 'Y-m-d H:i:s' ) );
var_dump( $int_end_date->format( 'Y-m-d H:i:s' ) );
I gladly accept better approaches if anyone has them.
You could try:
$now = time();
$interval = new DateInterval('P1W');
$interval_seconds = $interval->s + ($interval->i * 60) + ($interval->h * 60 * 60) + ($interval->d * 60 * 60 * 24);
$half_interval = round($interval_seconds / 2);
// Unix timestamps
$interval_start = $now - $half_interval;
$interval_end = $now + $half_interval;
EDIT: 2nd answer following on from comments
This only works for intervals of length 1 - eg 1 week, 1 year etc.
If your interval is > 1 then you'll need to somehow determine how far through the interval you are... e.g for a 2 week interval, are you in the first week or the second week?
$now = time();
$interval = "week";
switch ($interval) {
case "year":
$start_int = strtotime(date("Y", $now)."-01-01 00:00:00");
$end_int = strtotime(date("Y", $now)."-12-31 23:59:59");
break;
case "month":
$start_int = strtotime(date("Y-m", $now)."-01 00:00:00");
$end_int = strtotime(date("Y-m-t", $now)." 23:59:59");
break;
case "week":
$start_week = date("Y-m-d", strtotime("previous Monday", $now));
$end_week = date("Y-m-d", strtotime("next Sunday", $now));
$start_int = strtotime($start_week." 00:00:00");
$end_int = strtotime($end_week." 23:59:59");
break;
case "day":
$start_int = strtotime(date("Y-m-d", $now)." 00:00:00");
$end_int = strtotime(date("Y-m-d", $now)." 23:59:59");
break;
case "hour":
$start_int = strtotime(date("Y-m-d H", $now).":00:00");
$end_int = strtotime(date("Y-m-d H", $now).":59:59");
break;
case "minute":
$start_int = strtotime(date("Y-m-d H:i", $now).":00");
$end_int = strtotime(date("Y-m-d H:i", $now).":59");
break;
}
echo date("Y-m-d H:i:s", $start_int), "<br>";
echo date("Y-m-d H:i:s", $end_int), "<br>";
Update 3
I've put the logic from your answer into a single loop:
$start_date = new DateTime( '2013-01-01 00:00:00' );
$end_date = new DateTime( '2013-12-31 23:59:59' );
$end_date_ts = $end_date->getTimestamp();
$now = new DateTime( '2013-12-10 15:45:34' );
$now_ts = $now->getTimestamp();
$interval = new DateInterval( 'P1W' );
$period = new DatePeriod( $start_date, $interval, $end_date );
$int_start_date = $start_date;
$int_end_date = $end_date;
foreach ( $period as $dt ) {
$timestamp = $dt->getTimestamp();
if ($now_ts >= $timestamp) {
$int_start_date->setTimestamp($timestamp);
}
if ($now_ts < $timestamp and $timestamp < $int_end_date->getTimestamp()) {
$int_end_date->setTimestamp($timestamp - 1);
}
}
var_dump( $int_start_date->format( 'Y-m-d H:i:s' ) );
var_dump( $int_end_date->format( 'Y-m-d H:i:s' ) );

Categories