Represent a string of digits as days of the week - php

I have a 7 digit string of individual boolean values (e.g. 0010010), each digit representing a day of the week, Sunday to Saturday. If the day is active it's flagged as 1.
I want to check the string and output the abbreviated name of any days that are active.
Examples
1000000 is converted to Sun because the digit for Sunday is active.
0100010 is converted to MonFri
1111111 is converted to SunMonTueWedThuFriSatSun
I am using a system someone else designed here. What is the simplest method to achieve this with PHP?

I'll post this here, hoping that it may improve the question:
<?php
$dow =['mon','tue','wed','thu','fri','sat','sun'];
$day = '0010000';
$result = array_combine($dow, str_split($day));
var_export($result);
Output:
array (
'mon' => '0',
'tue' => '0',
'wed' => '1',
'thu' => '0',
'fri' => '0',
'sat' => '0',
'sun' => '0',
)
Further with the additional information:
$day = '1000100';
$result = array_combine($dow, str_split($day));
print implode(array_keys(array_filter($result)));
Output:
monfri

Related

CodeIgniter 2.1, PHP - find a day in array, take that day plus six more and remove the rest from the array

I have an array which represent all month. How can I find today's day in the array, take that day, plus next six days (not necessary six days) and remove rest from the array?
For example:
$days = array('1', '2', '3', ... '28', '29', '30');
I need 3-9. How can I do this?
I think you should look at another way of doing whatever it is you want to do. But here is a solution for what you asked:
$days = range(1, date('t'));
$days_forward = 6;
$key = array_search(date('j'), $days);
if($key === FALSE)
die('Date not found in array');
$days = array_slice($days, $key, $days_forward + 1);
print_r($days);
Output:
Array
(
[0] => 19
[1] => 20
[2] => 21
[3] => 22
[4] => 23
[5] => 24
[6] => 25
)

PHP get time period by timestamp

How can I get the time period (day, week, month) by a given timestamp? I do not want the date. I want the next time period based on the amount of seconds.
Is there a PHP native function for that?
Example:
$period = getTimeperiod( 15638400 );
My attempt: I could check and count the seconds:
if x <= 60 => min
if x <= 60*60 => hour
if x <= 60*60*24 => day
...
Edit:
Time period means either minute, hour, day, week, ... as stated above... ?! So all I want is the corresponding time period for a timestamp.
Example: (day = 86400 secs) then a timestamp with getTimeperiod( 85000 ) should be "day".
I think you're searching for something like the class DateInterval ...
It is part of PHP since 5.3.0 and has a static function called createFromDateString() where you can set up a DateInterval from a string like "3600 seconds". From this object you then can get the day, month, year and so on.
Take a look at this page:
http://www.php.net/manual/de/dateinterval.createfromdatestring.php
But is this on the right path returning an interval object (period)? Cred to #SimonSimCity for pointing out DateInterval. If you guide me I could improve the answer.
<?php
$timestamp = 15638400;
echo "The timestamp $timestamp is " . date("Y-m-d H:i:s", 15638400) . "<br \>";
echo "<pre>";
print_r (DateInterval::createFromDateString(date("Y \\y\\e\\a\\r\\s m \\m\\o\\n\\t\\h\\s d \\d\\a\\y\\s\\ H \\h\\o\\u\\r\\s i \\m\\i\\n\\u\\t\\e\\s s \\s\\e\\c\\o\\n\\d\\s", 15638400 ) ) );
echo "</pre>"
?>
Outputting
The timestamp 15638400 is 1970-07-01 00:00:00
DateInterval Object
(
[y] => 1970
[m] => 7
[d] => 1
[h] => 0
[i] => 0
[s] => 0
[invert] => 0
[days] => 0
)
I solved it that way:
/*
seconds 0
minutes 1
hours 2
days 3
week 4
month 5
year 6
decade 7
century 8
millenium 9
*/
$arTimes = array(
0 => 1,
1 => 60,
2 => 60*60,
3 => 60*60*24,
4 => 60*60*24*7,
5 => 60*60*24*7*4,
6 => 60*60*24*7*4*12,
7 => 60*60*24*7*4*12*10,
8 => 60*60*24*7*4*12*10*10,
9 => 60*60*24*7*4*12*10*10*10
);
$nDiff = strtotime( $nTo ) - strtotime( $nFrom );
switch( $nDiff )
{
// check difference and time period
case $nDiff <= $arTimes[ 1 ]:
$nGranularity = 0;
break;
...
}

date_parse_from_format to unix timestamp

I have a question regarding the date_parse_from_format() method:
$parsed = date_parse_from_format("Y d M H:i T", '2012 28 Nov 21:00 CET');
Returns associative array with detailed info about given date.
This will return an array with some date info. But is there any way to convert it to a unix timestamp?
Johan,
Heres an exact example of how to implement mktime into your scenario:
$parsed = date_parse_from_format("Y d M H:i T", '2012 28 Nov 21:00 CET');
$new = mktime(
$parsed['hour'],
$parsed['minute'],
$parsed['second'],
$parsed['month'],
$parsed['day'],
$parsed['year']
);
echo $new; //returns: 1354136400
For future reference, you can use var_dump() or print_r() on an array to see how to access the nested values.
var_dump of $parsed
array (size=16)
'year' => int 2012
'month' => int 11
'day' => int 28
'hour' => int 21
'minute' => int 0
'second' => int 0
'fraction' => boolean false
'warning_count' => int 0
'warnings' =>
array (size=0)
empty
'error_count' => int 0
'errors' =>
array (size=0)
empty
'is_localtime' => boolean true
'zone_type' => int 2
'zone' => int -60
'is_dst' => boolean false
'tz_abbr' => string 'CET' (length=3)
You can get the UNIX time-stamp by trying to use mktime() for a date.
For Example:
echo mktime(12, 20, 0, 10, 4, 2012 );
You will get the output like that 1349353200
And if you want AM/PM just add 12 to hours if PM.
For Example:
mktime($isAM ? $hrs : ($hrs + 12), $mins, $secs, $m, $d, $y);
and you can also use strtotime():
strtotime() - Parse about any English textual datetime description into a Unix timestamp
echo strtotime("2012-11-03 11:24:00PM");
You will get the output like that 1351985040
In PHP >=5.3, you can use the DateTime constructor which functions exactly like date_parse_from_format. Bonus points: it's a one-liner.
For instance, to convert a date in a UK format to a UNIX timestamp, we can do:
DateTime::createFromFormat("d/m/Y, H:i", '27/03/2020, 22:00')->getTimestamp()
-> int(1585346400)
mktime() should suit your needs perfectly :) Check out http://php.net/manual/en/function.mktime.php to see how you can use it!

Calculate number of days between two given dates

Can anyone correct the error in my script to calculate the number of days between 2 dates.
The dates have been input through a form, the variable info is as followed:
[departon] => Array ( [0] => 1 [1] => June [2] => 2011 )
[returnon] => Array ( [0] => 31 [1] => June [2] => 2011 )
I have written the code to calculate these dates, but its not calculating the day, it just outputs 0.
<?php
$first_date = mktime(12, 0, 0, $_POST['departon'][1], $_POST['departon'][0], $_POST['departon'][2]);
$second_date = mktime(12, 0, 0, $_POST['returnon'][1], $_POST['returnon'][0], $_POST['returnon'][2]);
$days = $second_date-$first_date;
echo floor($days/60/60/24) . " days";
?>
Help would be much appreciated.
The easiest way is by using datetimes.
Consider this:
var_dump(new DateTime('1 July 2007'));
$a = new DateTime('1 July 2007');
$b = new DateTime('1 June 2001');
var_dump($a->diff($b));
The var_dump will allow you to see the different kind of time you can extract from it.
object(DateInterval)[3]
public 'y' => int 6
public 'm' => int 1
public 'd' => int 0
public 'h' => int 0
public 'i' => int 0
public 's' => int 0
public 'invert' => int 1
public 'days' => int 2221
You can convert your array to a date time very easily by using
$date = new DateTime(join(" ",$array));
$date2 = new DateTime(join(" ",$array2));
$diff = $date->diff($date2);
Here's an easy way:
$depart = strtotime(implode(' ', $_POST['departon']));
$return = strtotime(implode(' ', $_POST['returnon']));
$diff = floor(($return - $depart) / (60 * 60 * 24));
Note: there's only 30 days in June.
The mktime documentation specifies a number for the month, so you'd need to convert 'June' to '6'.

break apart formatted date into individual month/day/year hour/minute/second in php

I have a date in the following format
November 18, 2009, 3:00PM
How can i break that up so that i can store each value as its own variable?
such as...
$month //November
$day //18
$year //2009
$hour //03
$minute //00
$ampm //PM
Use the 'date_parse' (http://nl2.php.net/manual/en/function.date-parse.php) function. It returns an array with the parsed items:
Array
(
[year] => 2006
[month] => 12
[day] => 12
[hour] => 10
[minute] => 0
[second] => 0
[fraction] => 0.5
[warning_count] => 0
[warnings] => Array()
[error_count] => 0
[errors] => Array()
[is_localtime] =>
)
Convert your date into a timestamp, then with the timestamp you can easily get your parts. An other way is using a regular expression.
$str = "November 18, 2009, 3:00PM";
list($month,$day,$year,$time) = preg_split('/[ ,]/',$str,false,PREG_SPLIT_NO_EMPTY);
preg_match('/([0-9]+):([0-9]+)([AP]M)/',$time,$timeparts);
list($time,$hour,$minute,$ampm) = $timeparts;
echo "\$month $month\n";
echo "\$day $day\n";
echo "\$year $year\n";
echo "\$hour $hour\n";
echo "\$minute $minute\n";
echo "\$ampm $ampm\n";
Output
$month November
$day 18
$year 2009
$hour 3
$minute 00
$ampm PM
More complex solution.
If your dates may be in the different standards you can use date() function (http://php.net/manual/en/function.date.php) + strtotime() function (http://php.net/manual/en/function.strtotime.php), which parse string and returns the unix timestamp.
For example, if you want to get a year from your date string you could write next code:
$date = 'November 18, 2009, 3:00PM';
$year = date('Y', strtotime($date));
Or, if you want to know how much days in the month in date you get, you could write such code:
$date = 'November 18, 2009, 3:00PM';
$num_of_days = date('t', strtotime($date));
't' returns the number of days in the given month.

Categories