Given the information below:
Year: 2012
Weeknumber: 4
Dayname: TUE
How can i convert this to a valid date like 2012-01-12 (YYYY-MM-DD) using PHP's date functions?
Thanx
The DateTime class can't do this, but the function strptime can.
$d = strptime('TUE 4 2012', '%a %W %Y');
var_dump($d);
That returns an array:
array
'tm_sec' => int 0
'tm_min' => int 0
'tm_hour' => int 0
'tm_mday' => int 24
'tm_mon' => int 0
'tm_year' => int 112
'tm_wday' => int 2
'tm_yday' => int 23
'unparsed' => string '' (length=0)
Note that tm_year contains the number of years since 1900 and tm_month is 0-based, not 1-based. So this does represent 2012-01-24, which is correct.
Use this function:
function get_date($year,$week,$day,$start_sunday=false){
$day_array = array('Mon'=>1,'Tue'=>2,'Wed'=>3,'Thu'=>4,'Fri'=>5,'Sat'=>6,'Sun'=>($start_sunday?0:7));
$month_array = array(31,($year%4==0?29:28),31,30,31,30,31,31,30,31,30,31);
$week *= 7;
$month = 1;
for($i=0;$i<count($month_array);$i++){
if($week-$month_array[$i]<=0){
break;
}
$week -= $month_array[$i];
$month++;
}
$format = "$year $month $week";
$date = date_create_from_format("Y m j",$format);
$date_num = date_format($date,"D");
$curr = $day_array[ucfirst(strtolower($day))]-$day_array[$date_num];
$got_date = strtotime("$curr ".($curr==1||$curr==-1?"day":"days"),strtotime(date_format($date,"Y-m-j")));
return $got_date;
}
where $start_sunday should be true if week starts from sunday
$year is the year
$week is week number
$day is short weekday name i.e.mon,tue,wed,....
this function will get you a date form the given format.
Enjoy............
Related
I need to add days (input type number + input type date) but the result must be an array so I can INSERT one after another into the Database.
Here's the code (After HTML Form submitted):
<?php
$start_date = '2017-12-22';
$duration = '3';
$d = new DateTime($start_date);
$t = $d->getTimestamp();
// loop for X days
for($i=0; $i <= $duration; $i++){
// add 1 day to timestamp-
$addDay = 86400;
// get what day it is next day
$nextDay = date('w', ($t + $addDay));
// if it's Saturday or Sunday get $i-1
if($nextDay === 6 || $nextDay === 7) {
$i --;
}
// modify timestamp, add 1 day
$t = $t + $addDay;
$d->setTimestamp($t);
$day_off = $d->format( 'Y-m-d' ). "<br />";
echo $day_off;
$query = "INSERT SQL";
}
?>
From echo $day_off result I get:
2017-12-23
2017-12-24
2017-12-25
2017-12-26
Instead of 23, 24, 25, 26. I need to get the result below:
2017-12-22
2017-12-25
2017-12-26
2017-12-27
22 is the input date, start from 25 because 23 and 24 are Sat and Sun and weekends need to be excluded.
How can I achieve this result? I've been searching on the net but unfortunately, I couldn't find what I needed.
#C. Geek answer made it to works, but I have a more complex question here, since my account are not eligible to ask more question so I'll ask here.
So here's what I've tried so far (with #C. Geek answer) :
<?php
// loop for X days
for($i=0; $i < $duration; $i++){
$d = strtotime("$start_date +$i weekdays");
$t = strftime("%Y-%m-%d",$d);
$day_off[] = $t;
foreach($day_off as $dayoff) {
$data_holiday = mysqli_fetch_array(mysqli_query($con, "SELECT * FROM `holiday_master_data` WHERE `date` = '$dayoff' "));
}
$holiday[] = $data_holiday['date'];
$date = array_diff($day_off, $holiday);
$dayoff_ = $holiday;
?>
Start date : 2017-12-29
Duration : 5 days
From print_r($day_off); I'm getting this result :
Array ( [0] => 2017-12-29 ) Array ( [0] => 2017-12-29 [1] => 2018-01-01 ) Array ( [0] => 2017-12-29 [1] => 2018-01-01 [2] => 2018-01-02 )
And from print_r($holiday); I'm getting this result :
Array ( [0] => ) Array ( [0] => [1] => 2018-01-01 ) Array ( [0] => [1] => 2018-01-01 [2] => ) Array ( [0] => [1] => 2018-01-01 [2] => [3] => ) Array ( [0] => [1] => 2018-01-01 [2] => [3] => [4] => )
The national date fetched from database is 2018-01-01 with 5 looping result, the final date result I need to make are 29 Dec, 02 Jan 03 Jan and 04 Jan, 05 Jan.
Any help will be much appreciated.
Thanks.
https://stackoverflow.com/a/4261223/6288442
If you are limiting to weekdays use the string weekdays.
echo date ( 'Y-m-j' , strtotime ( '3 weekdays' ) );
This should jump you ahead by 3 weekdays, so if it is Thursday it will
add the additional weekend time.
Source: http://www.php.net/manual/en/datetime.formats.relative.php
As for formatting:
http://php.net/manual/en/function.strftime.php
string strftime ( string $format [, int $timestamp = time() ] )
If you need more help with writing the code than these, please do tell in a comment
Here is my full answer:
$start_date = '2017-12-22';
$duration = 3;
$arr=null;
for($i=0; $i <= $duration; $i++){
$d = strtotime("$start_date +$i weekdays");
$t = strftime("%Y-%m-%d",$d);
$arr[]=$t;
}
Get the holidays before the looping, then in the loop, check if date is in_array before adding it to $arr.
e.g.
$start_date = '2017-12-22';
$data_holiday = mysqli_fetch_array(mysqli_query($con, "SELECT * FROM `holiday_master_data` WHERE YEAR(`date`) BETWEEN YEAR('$start_date') AND YEAR('$start_date')+1 "));
$holidays =
$duration = 3;
$arr=null;
for($i=0; $i <= $duration; $i++){
$d = strtotime("$start_date +$i weekdays");
$t = strftime("%Y-%m-%d",$d);
if(!in_array($t,$data_holiday))
$arr[]=$t;
}
FINALLY!! After several hours I fixed everything. Here's the code how I manage to skip (Sun and Monday) and also Skip the Holiday's fetched from the database (based on #C.Geek answers + several tweaking):
<?php
include 'conn.php';
$start_date = mysqli_real_escape_string($con, $_POST['start_date']);
$duration = mysqli_real_escape_string($con, $_POST['duration']);
// loop for X days
for($i=0; $i <= $duration; $i++){
$d = strtotime("$start_date +$i weekdays");
$t = explode(", ", strftime("%Y-%m-%d", $d));
foreach ($t as $date) {
$to_encode = array("date" => $date);
$date_where = $to_encode['date'];
$data_holiday = mysqli_fetch_array(mysqli_query($con, "SELECT `date` AS '0' FROM `holiday_master_data` WHERE DATE(`date`) BETWEEN DATE('$date_where') AND DATE('$date_where') + 1 GROUP BY `id` "));
$encode_holiday = array("date" => $data_holiday[0]);
break;
}
$holiday = array_unique($encode_holiday);
$dayoff = array_diff($t, $holiday);
foreach($dayoff as $date) {
$query = mysqli_query($con, "INSERT INTO ");
if ($query) {
echo "<script>alert('Absence Saved'); window.location ='document.php' </script>";
} else {
echo "<script>alert('Gagal'); window.location ='document.php' </script>";
}
}
}
?>
Hope this helps anyone seeking the same problem I had.
Cheers.
I have an array like so
array (size=5107)
0 => int 421
1 => int 996
2 => int 1555
3 => int 399
4 => int 57914
5 => int 57245
6 => int 7176
7 => int 7166
8 => int 5987
This array is being generated by pulling some timestamps from a database, comparing them and then getting the difference in seconds like so;
$start_date = new DateTime($startdate);
$since_start = $start_date->diff(new DateTime($closedate));
$diff = strtotime($closedate) - strtotime($startdate);
I then want to get the average of the array, but whenever I do a array_sum($array); the result is always negative and I'm not sure why. What am I misunderstanding here?
If I change
$diff = strtotime($closedate) - strtotime($startdate);
To
$diff = strtotime($startdate) - strtotime($closedate);
The array_sum($array); results in a positive value but all the array values are negative but all the results are the same.
You should get the absolute value:
$diff = abs(strtotime($closedate) - strtotime($startdate));
I have a number of variables that store a year, month and series of dates for that month (there are 2 of these for 2 separate months). I then need to incorporate these into what I believe is a multidimensional array (haven't worked with these types of arrays before). Here's my code that has the variables:
// Set the default timezone
date_default_timezone_set('Australia/Sydney');
$month1 = date('m');
$year1 = date('Y');
$dates1 = '3 5 6 10 12 13 17 19 20 24 26 27 31';
$month2 = date('m', strtotime('first day of next month')) ;
$year2 = date('Y', strtotime('first day of next month')) ;
$dates2 = '10 15 26';
Using Dec 10, 2013 as the current date and the above list of dates I then need to end up with an array in this format:
array("year" => array("month" => array(days)));
that would look like this:
$daysArray = array ("2013" => array("12" => array(3,5,6,10,12,13,17,19,20,24,26,27,31)), "2014" => array("1" => array(10,15,26)));
I'm not sure how to convert these 6 variables into a multidimensional array?
Considering a few edge cases as well (same year etc), i think this is a rather simple (readable) solution:
// Sample data
$month1 = 12;
$year1 = 2013;
$dates1 = '3 5 6 10 12 13 17 19 20 24 26 27 31';
$month2 = 1;
$year2 = 2014;
$dates2 = '10 15 26';
$result = combineDateArrays(createDateArray($year1, $month1, $dates1), createDateArray($year2, $month2, $dates2));
function createDateArray($year, $month, $dates) {
return array($year=>array($month=>explode(" ", $dates)));
}
function combineDateArrays($dateArray1, $dateArray2) {
foreach($dateArray2 as $year=>$months) {
foreach($months as $month=>$days) {
if (!isset($dateArray1[$year])) $dateArray1[$year] = array();
$dateArray1[$year][$month] = $days;
}
}
return $dateArray1;
}
You can create an array from a string using explode:
$daysArray = array($year1 => $month1 => explode(' ', $dates1), $year2 => $month2 => explode(' ', $dates2));
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'.
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.