Sort array of days from a specific start date - php

I have this array of days in a random order :
$jour_planning[] = "friday";
$jour_planning[] = "wednesday";
$jour_planning[] = "monday";
$jour_planning[] = "tuesday";
$jour_planning[] = "thursday";
$jour_planning[] = "sunday";
$jour_planning[] = "saturday";
If we are today a "tuesday", I would like to have this new array :
$jour_planning[] = "wednesday";
$jour_planning[] = "thursday";
$jour_planning[] = "friday";
$jour_planning[] = "saturday";
$jour_planning[] = "sunday";
$jour_planning[] = "monday";
$jour_planning[] = "tuesday";
How can do that, with usort() ?
Regards,
Vianney

I would first sort the array (and avoid french and english naming :) ).
Then, loop that sorted array and store into 2 separates array the days before the expected one (including this one), and the days after.
And finally, merge both arrays.
There's certainly better ways to do that.
$jour_planning[] = "friday";
$jour_planning[] = "wednesday";
$jour_planning[] = "monday";
$jour_planning[] = "tuesday";
$jour_planning[] = "thursday";
$jour_planning[] = "sunday";
$jour_planning[] = "saturday";
$sorted_days_planning = array(1 => null, 2 => null, 3 => null, 4 => null, 5 => null, 6 => null, 7 => null);
foreach ($jour_planning as $value)
{
$day_of_week = date('N', strtotime($value));
$sorted_days_planning[$day_of_week] = $value;
}
$final_days_planning = array();
$day_to_start = "tuesday";
$day_found = false;
$temp_array = array();
foreach ($sorted_days_planning as $value)
{
if (!$day_found)
{
$temp_array[] = $value;
if ($day_to_start == $value)
$day_found = true;
}
else
$final_days_planning[] = $value;
}
$final_days_planning = array_merge($final_days_planning, $temp_array);
var_dump($final_days_planning);
Outputs :
array(6) {
[0]=> string(9) "wednesday"
[1]=> string(8) "thursday"
[2]=> string(6) "friday"
[3]=> string(8) "saturday"
[4]=> string(6) "sunday"
[5]=> string(6) "monday"
[6]=> string(7) "tuesday"
}

You can rearrange your array using uksort(), date() and strtotime().
function sort_week_days( $t1, $t2 ) {
$weekdays = array( 'sunday', 'monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday' );
foreach ( $weekdays as $key => $value ) {
$weekdays[ $key ] = date( 'w', strtotime( $value ) );
}
$t1_time = date( 'w', strtotime( strtolower( $t1 ) ) );
$t2_time = date( 'w', strtotime( strtolower( $t2 ) ) );
return array_search( $t1_time, $weekdays ) - array_search( $t2_time, $weekdays );
}
You need to pass your random array as below :
usort($jour_planning, "sort_week_days");
Then you can used your array in below code :
$day = date('w'); // You need to change to date('w', '-1day'); get result from today.
for ($i=0; $i <= $day ; $i++) {
array_push($jour_planning, array_shift($jour_planning));
}

Because of your array is randomly ordered, there is no other way to order it correctly, then doing it by hand (you cannot order the array numerically or alphabetically - it can be done by calculating the days by the datetime() function, see #Cid's answer), so:
/*
$jour_planning = [];
$jour_planning[] = "friday";
$jour_planning[] = "wednesday";
$jour_planning[] = "monday";
$jour_planning[] = "tuesday";
$jour_planning[] = "thursday";
$jour_planning[] = "sunday";
$jour_planning[] = "saturday";
*/
$days = [
0 => 'monday',
1 => 'tuesday',
2 => 'wednesday',
3 => 'thursday',
4 => 'friday',
5 => 'saturday',
6 => 'sunday'
];
$today = array_search(strtolower(date('l')), $days);
$tomorrow = ($today === 6) ? 0 : $today + 1;
$reordered = array_merge(array_slice($days, $tomorrow), array_slice($days, 0, $tomorrow));
print_r($reordered);
Firstly you have to search the current day, then add 1 to the index of this day and you have the day, that will be tomorrow. Now, when you have this index, you simply create 2 arrays: the first one starting from the day of tomorrow and the second one starting from index 0 to the day of today. Then merge this two arrays together and you have exactly what you wanted to have.

You can use this function to sort week days and it's has option to include the first day.
function sort_days($day_to_start = 'monday', $include_first_day = true)
{
$final_days_planning = [];
$rest_days = [];
$first_day_found = 0;
foreach ([ "sunday", "monday", "tuesday", "wednesday", "thursday", "friday", "saturday" ] as $day)
{
if (!$first_day_found){
if ($day_to_start == $day){
$first_day_found = 1;
if($include_first_day){
$final_days_planning[] = $day;
}
else
{
$rest_days[] = $day;
}
}
else
{
$rest_days[] = $day;
}
} else{
$final_days_planning[] = $day;
}
}
return array_merge($final_days_planning, $rest_days);
}
To try it:
$days = sort_days('wednesday');
print_r($days);

You can use in_array to find the days present in your array and add to new array.
$jour_planning=["saturday","wednesday","friday","thursday"];
public function getSortedDays($jour_planning){
$sorted_days=[];
for($i=1;$i<=7;$i++){
$day = date("l", strtotime("+$i days"));
$_day = strtolower($day);
if(in_array($_day, $jour_planning)){
$sorted_days[] = $_day;
}
}
return $sorted_days;
}
$sorted_days = getSortedDays($jour_planning);
print_r($sorted_days); //Array ( [0] => wednesday [1] => thursday [2] => friday [3] => saturday )

while (end($jour_planning) !== "tuesday") {
array_unshift($jour_planning, array_pop($jour_planning));
}

Related

Calculate Appointments beetween two dates

Situation:
I have arrays with information of the used appointments and the calculated days for the new appointment series based on PHP.
For example, the exist appointment array:
Array
(
[0] => Array
(
[date] => 2019-05-02
[time_start] => 14:00:00
[time_end] => 15:30:00
)
[1] => Array
(
[date] => 2019-05-06
[time_start] => 14:00:00
[time_end] => 15:30:00
)
)
Now, i will check have the calculated series (same array format) collisions with the exist appointments.
My Question:
How can i check if a collision exist beetween the start and end time and if yes how i can give the array a new value with a time windows after or before the exist appointment. This within a time windows from 08:00 am to 4:00 pm.
What i have is the calculation of the appointment days.
private function calculate_dates($data, $measure)
{
$this->load->model('calendar/calendar_model');
$holiday_dates = $this->calendar_model->get_holidays();
foreach ($holiday_dates as $key => $value) {
$holidays[] = $value['holiday_date'];
}
$begin = new DateTime($data->measure_begin);
$end = new DateTime($data->measure_end);
$oneday = new DateInterval("P1D");
$days = json_decode($data->measure_dates);
$wdays = array();
$ue_minutes = 0;
$minutes = ($data->measure_ue * $measure->ue_minutes/2);
$daterange = new DatePeriod( $begin, DateInterval::createFromDateString('+1 weekdays') ,$end );
foreach(new DatePeriod($begin, $oneday, $end->add($oneday)) as $day) {
$day_num = $day->format("N"); /* 'N' number days 1 (mon) to 7 (sun) */
if($day_num < 6 ) { /* weekday */
$wdays[] = $day;
}
}
$count = 1;
foreach($wdays as $date){
foreach ($days as $key => $value) {
if(mb_strtolower($date->format('l')) == $value){
if(($data->measure_ue/2)+1 != $count){
if(in_array($date->format('Y-m-d'), $holidays)) {
$dates[] = $this->close_days($date, $days, true)->format('l, d.m.Y');
} else {
$dates[] = $date->format('l, d.m.Y');
}
$count++;
}
}
}
}
return array(
'dates' => $dates,
'minutes' => round($minutes/count($dates))
);
}
private function close_days($date, $days, $init = false)
{
if($init){
$days[] = 'saturday';
$days[] = 'sunday';
}
if( in_array(mb_strtolower($date->format('l')), $days) ) {
$this->close_days($date->modify('next day'), $days);
}
return $date;
}
Any Ideas for a solution or maybe a code for a better way?

How To Remove Duplicate Elements from array after merging with another array in php?

I am trying to Write Program for Calculating Next 20 dates After Specifying Start date, then from 20 dates i have Exclude Weekends & Holidays(Array holidays('2016-12-13',2016-12-24)) And Result Array which includes only Working Days Excluding Saturday & Sunday, from this Result Array after Passing Holiday array(Eg:- holidays('2016-12-13',2016-12-24))), it must be Excluded from result array. i:e;
I want Expected Output Below mentioned
.
<?php
$Date=array('2016-12-01');
echo "\n <br />Start Date:-" . $Date[0] . "";
/*Code For Generating Next 20 Dates Starts*/
//$start = strtotime($s_row['schedule_start_date']);
$start = strtotime('2016-12-01');
$dates=array();
for($i = 0; $i<20; $i++)
{
array_push($dates,date('Y-m-d', strtotime("+$i day", $start)));
}
echo "\n <br /> Array Of next 20 Days/dates of Given:-";
print_r($dates);
$start=array();
$start=$dates; /*Code For Generating Next 20 Dates Ends*/
$result=array();
$start = strtotime(array_values($Date)[0]);
//$end = strtotime(array_values($Date)[30]);
$result = array();
$begin = new DateTime( '2016-12-01' );
$end = new DateTime( '' );
//$end = $end->modify( '+1 day' );
$interval = new DateInterval('P1D');
$daterange = new DatePeriod($begin, $interval ,$end);
foreach($daterange as $date)
{
//echo $date->format("Y-m-d") . "<br>";
if (date('N', $start) <= 5) /* 'N' number days 1 (mon) to 7 (sun) */
/*5 weekday */
{
$current = date('Y-m-d', $start); //m/d/Y
$result[$current] = '';
}
$start += 86400;
//echo "Days Without Sat Sun".$result[date($date->format("Y-m-d"))];
//echo "Days Without Sat Sun".$result2[date($current->format("Y-m-d"))];
}
echo " \n <br /> Dates Without Weekends LIKE (Excluding Saturday & Sunday):-";
print_r($result);
/*For Holiday*/
$FinalArray = array();
$holidays = array(
'2016-12-13',
'2016-12-24',
);
echo " \n <br /> Given Holiday Dates Are:-";
print_r($holidays);
$a1 = $result;
$a2 = $holidays;
$array = array_diff(array_merge($a1,$a2),array_intersect($a1,$a2));
echo "\n <br /> Output:-";
print_r($array);
?>
it Gives Output as :- Array ( [2016-12-01] => [2016-12-02] => [2016-12-05] => [2016-12-06] => [2016-12-07] => [2016-12-08] => [2016-12-09] => [2016-12-12] => [2016-12-13] => [2016-12-14] => [2016-12-15] => [2016-12-16] => [2016-12-19] => [2016-12-20] => [2016-12-21] => [2016-12-22] => [2016-12-23] => [0] => 2016-12-13 [1] => 2016-12-24 )
> But I Want Expected Output:-
Array ( [2016-12-01] => [2016-12-02] => [2016-12-05] => [2016-12-06] => [2016-12-07] => [2016-12-08] => [2016-12-09] => [2016-12-12] => [2016-12-14] => [2016-12-15] => [2016-12-16] => [2016-12-19] => [2016-12-20] => [2016-12-21] => [2016-12-22] => [2016-12-23]
You Can Notice That 2016-12-13 is Not There in Above Expected Output as in '2016-12-13', 2016-12-24 is passed as Holiday via holiday array ($holidays = array( '2016-12-13', '2016-12-24', );) i:e; if i pass any date through holidays array it should not be included in result Array(). i:e 2016-12-13 is Available in Result array as well as holiday array So While while printing Final OUTPUT:- 13th date(2016-12-13) Should not be Included in final Output. Anybody Solve this will be Appreciated Thanks in Advance.
When I have to remove duplicates from a array the function that I keep going back to is
array array_unique ( array $array [, int $sort_flags = SORT_STRING ] )
you can find the documentation Here
<?php
$input = array("a" => "green", "red", "b" => "green", "blue", "red");
$result = array_unique($input);
print_r($result);
?>
the output
Array
(
[a] => green
[0] => red
[1] => blue
)
I hope that this was able to help
I prefer to calculate all dates just in one pass. (You may skip filling $dates and $dates_mon_fri arrays if they doesn't used in output also.) There is yet another approach to avoid array_diff() and array_unique() functions. I've used an array_flip() to exchange keys with values in $holdidays array to use fast array_key_exists() function.
<?php
$start = strtotime('2016-12-01');
$holidays = [
'2016-12-13',
'2016-12-24',
];
$dates = [];
$dates_mon_fri = [];
$dates_working = [];
$flip_holidays = array_flip($holidays);
for ($i = 0; $i < 20; $i++) {
$timestamp = strtotime("+$i day", $start);
$date = date('Y-m-d', $timestamp);
$dates[] = $date;
$mon_fri = false;
if (date('N', $timestamp) <= 5) {
$dates_mon_fri[] = $date;
$mon_fri = true;
}
if ($mon_fri && !array_key_exists($date, $flip_holidays)) {
$dates_working[] = $date;
}
}
var_dump($dates);
var_dump($dates_mon_fri);
var_dump($dates_working);
You can avoid using explicit looping:
$begin = new DateTimeImmutable('2016-12-01');
$end = $begin->modify('+20 days');
$interval = new DateInterval('P1D');
$daterange = new DatePeriod($begin, $interval, $end);
$allDates = iterator_to_array($daterange);
$datesExcludingWeekends = array_filter($allDates, function ($date) {
return (int) $date->format("N") < 6;
});
$datesExcludingWeekends = array_map(
'date_format',
$datesExcludingWeekends,
array_fill(1, count($datesExcludingWeekends), 'Y-m-d')
);
$holidays = [
'2016-12-13',
'2016-12-24',
];
$datesExcludingWeekendsIncludingHolidays = array_flip(array_merge(
$datesExcludingWeekends,
array_diff($holidays, $datesExcludingWeekends)
));
Here is working demo.
Also, take a look at the Carbon library. If you need some exhaustive working with dates this library can really ease your life.

repeat event by days with occurrences

<?php
function getDateOfWeekDay($day) {
$weekDays = array(
'Sunday',
'Monday',
'Tuesday',
'Wednesday',
'Thursday',
'Friday',
'Saturday',
);
$dayNumber = array_search($day, $weekDays);
$currentDayNumber = date('w', strtotime('today'));
// if ($dayNumber > $currentDayNumber) {
if ( $currentDayNumber > $dayNumber) {
//return date('Y-m-d', strtotime($day));
echo date('Y-m-d',strtotime($day.' this week'));
} else {
//return date('Y-m-d', strtotime($day) + 604800);
echo date('Y-m-d',strtotime($day.' next week') +1);
}
}
$ron="0,2,6"; // $ron is repeats on every sunday , tuesday, and saturday
$oc=4; // $oc is an occurrences how many time it will repeat
$ronS=explode(',', $ron);
foreach($ronS as $ronS) {
$res[]= $ronS;
}
$r=0;
$rr=0;
for($i = 0; $i < $oc; $i++)
{
if($i<count($res))
{
$t=$res[$i];
$r++;
}
else
{
$t=$res[$rr];
$rr++;
}
$week = array('0'=>"Sunday","1"=>"Monday","2"=>"Tuesday","3"=>"Wednesday","4"=>"Thursday","5"=>"Friday","6"=>"Saturday");
$day[] = $week[$t];
}//for
print_r($day);
foreach ($day as $da)
{
echo getDateOfWeekDay($da)."\n";
}
?>
the output of this code is
Array
(
[0] => Sunday
[1] => Tuesday
[2] => Saturday
[3] => Sunday
)
2014-05-18
2014-05-20
2014-05-24
2014-05-18
All working fine but the last date 2014-05-18 is wrong it will be 2014-05-25

Most efficient way to get array of months in array of years

What is the most efficient way to get an array of months, from a specified date, up until the present day, grouped by year.
Eg getMonths("August 2012") would output
array(
array("Year"=>"2013", "months" = array(
"February", "January")
),
array("Year"=>"2012", "months" = array(
"December", "November","October", "September", "August")
)
)
So far I've got:
$start = strtotime('2012-08-01');
$end = time();
$month = $start;
$months[] = date('F', $start);
while($month <= $end) {
$month = strtotime("+1 month", $month);
$months[] = date('F', $month);
}
This is outputting the correct months, but not grouping them into years.
Thanks
You can try
function getMonths($month,$count = 1) {
$now = new DateTime();
$start = DateTime::createFromFormat("F Y", $month);
$list = array();
$interval = new DateInterval(sprintf("P%dM",$count));
while ( $start <= $now ) {
$list[$start->format("Y")][] = $start->format("F");
$start->add($interval);
}
return $list;
}
print_r(getMonths("August 2012"));
Output
Array
(
[2012] => Array
(
[0] => August
[1] => September
[2] => October
[3] => November
[4] => December
)
[2013] => Array
(
[0] => January
[1] => February
)
)
Since the answer posted here did not work for me (also tried online sandbox to be sure) i wrote a method that works with the very most versions of PHP:
function getMonths($monat, $year) {
$list = array();
for(;$monat <= 12;$monat++) {
if($year == date("Y") && $monat == date("m")) { // exit on current month+year
break;
}
if(!isset($list[ $year ])) {
$list[ $year ] = array();
}
$list[ $year ][ str_pad($monat, 2, '0', STR_PAD_LEFT) ] = date("F", strtotime('01.' . $monat . '.' . $year));
if($monat == 12) {
$monat = 0;
$year++;
}
}
return $list;
}

Display dates in Arabic

Here's my code:
setlocale( LC_ALL,'ar' );
echo strftime( '%e %b, %Y', strtotime( '2011-10-25' ));
Output:
25 Sep, 2011
Why is it not displaying the arabic date? Am I using strftime incorrectly?
Here you can print the Arabic PHP Date :
Create a file called arabicdate.php and place this function inside it :
function ArabicDate() {
$months = array("Jan" => "يناير", "Feb" => "فبراير", "Mar" => "مارس", "Apr" => "أبريل", "May" => "مايو", "Jun" => "يونيو", "Jul" => "يوليو", "Aug" => "أغسطس", "Sep" => "سبتمبر", "Oct" => "أكتوبر", "Nov" => "نوفمبر", "Dec" => "ديسمبر");
$your_date = date('y-m-d'); // The Current Date
$en_month = date("M", strtotime($your_date));
foreach ($months as $en => $ar) {
if ($en == $en_month) { $ar_month = $ar; }
}
$find = array ("Sat", "Sun", "Mon", "Tue", "Wed" , "Thu", "Fri");
$replace = array ("السبت", "الأحد", "الإثنين", "الثلاثاء", "الأربعاء", "الخميس", "الجمعة");
$ar_day_format = date('D'); // The Current Day
$ar_day = str_replace($find, $replace, $ar_day_format);
header('Content-Type: text/html; charset=utf-8');
$standard = array("0","1","2","3","4","5","6","7","8","9");
$eastern_arabic_symbols = array("٠","١","٢","٣","٤","٥","٦","٧","٨","٩");
$current_date = $ar_day.' '.date('d').' / '.$ar_month.' / '.date('Y');
$arabic_date = str_replace($standard , $eastern_arabic_symbols , $current_date);
return $arabic_date;
}
Now include this file in your page :
include 'arabicdate.php';
Then you can print the Arabic PHP Date :
echo ArabicDate();
Live Formatted Example :
http://ideone.com/MC0hou
Hope that helps.
How about this:
function arabicDate($time)
{
$months = ["Jan" => "يناير", "Feb" => "فبراير", "Mar" => "مارس", "Apr" => "أبريل", "May" => "مايو", "Jun" => "يونيو", "Jul" => "يوليو", "Aug" => "أغسطس", "Sep" => "سبتمبر", "Oct" => "أكتوبر", "Nov" => "نوفمبر", "Dec" => "ديسمبر"];
$days = ["Sat" => "السبت", "Sun" => "الأحد", "Mon" => "الإثنين", "Tue" => "الثلاثاء", "Wed" => "الأربعاء", "Thu" => "الخميس", "Fri" => "الجمعة"];
$am_pm = ['AM' => 'صباحاً', 'PM' => 'مساءً'];
$day = $days[date('D', $time)];
$month = $months[date('M', $time)];
$am_pm = $am_pm[date('A', $time)];
$date = $day . ' ' . date('d', $time) . ' - ' . $month . ' - ' . date('Y', $time) . ' ' . date('h:i', $time) . ' ' . $am_pm;
$numbers_ar = ["٠", "١", "٢", "٣", "٤", "٥", "٦", "٧", "٨", "٩"];
$numbers_en = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9'];
return str_replace($numbers_en, $numbers_ar, $date);
}
Note: the parameter ($time) should be Unix timestamp.
AFAIK setlocale won't actually do any language translation for you but rather affects things like the formatting and comparator functionality. If you want localisation then you could try using IntlDateFormatter which may give you what you need.
Updated: You could also try Zend_Date as suggested in this question if PHP 5.3 isn't an option for you.
Inspired by Amr SubZero's answer above:
If anybody else needed this, these two functions displays post date and time in arabic for a wordpress website:
DATE:
functions.php
function single_post_arabic_date($postdate_d,$postdate_d2,$postdate_m,$postdate_y) {
$months = array("Jan" => "يناير", "Feb" => "فبراير", "Mar" => "مارس", "Apr" => "أبريل", "May" => "مايو", "Jun" => "يونيو", "Jul" => "يوليو", "Aug" => "أغسطس", "Sep" => "سبتمبر", "Oct" => "أكتوبر", "Nov" => "نوفمبر", "Dec" => "ديسمبر");
$en_month = $postdate_m;
foreach ($months as $en => $ar) {
if ($en == $en_month) { $ar_month = $ar; }
}
$find = array ("Sat", "Sun", "Mon", "Tue", "Wed" , "Thu", "Fri");
$replace = array ("السبت", "الأحد", "الإثنين", "الثلاثاء", "الأربعاء", "الخميس", "الجمعة");
$ar_day_format = $postdate_d2;
$ar_day = str_replace($find, $replace, $ar_day_format);
header('Content-Type: text/html; charset=utf-8');
$standard = array("0","1","2","3","4","5","6","7","8","9");
$eastern_arabic_symbols = array("٠","١","٢","٣","٤","٥","٦","٧","٨","٩");
$post_date = $ar_day.' '.$postdate_d.' '.$ar_month.' '.$postdate_y;
$arabic_date = str_replace($standard , $eastern_arabic_symbols , $post_date);
return $arabic_date;
}
Inside the loop:
<date>
<?php
$postdate_d = get_the_date('d');
$postdate_d2 = get_the_date('D');
$postdate_m = get_the_date('M');
$postdate_y = get_the_date('Y');
echo single_post_arabic_date($postdate_d,$postdate_d2, $postdate_m, $postdate_y);
?>
</date>
TIME:
functions.php
function single_post_arabic_time($posttime_h, $posttime_i, $posttime_a) {
$ampm = array("AM", "PM");
$ampmreplace = array("ق.ظ", "ب.ظ");
$ar_ampm = str_replace($ampm, $ampmreplace, $posttime_a);
header('Content-Type: text/html; charset=utf-8');
$standardletters = array("0", "1", "2", "3", "4", "5", "6", "7", "8", "9");
$eastern_arabic_letters = array("٠", "١", "٢", "٣", "٤", "٥", "٦", "٧", "٨", "٩");
$post_time = $posttime_h . ':' . $posttime_i." ".$ar_ampm;
$arabic_time = str_replace($standardletters, $eastern_arabic_letters, $post_time);
return $arabic_time;
}
Inside the loop:
<span>الساعة </span>
<time>
<?php
$posttime_h = get_the_date('h');
$posttime_i = get_the_date('i');
$posttime_s = get_the_date('d');
$posttime_a = get_the_date('A');
echo single_post_arabic_time($posttime_h,$posttime_i,$posttime_a);
?>
</time>
if all you're looking for is to print what day is today, then your question is easy...
Try this function.
<?php
function arDate(){
$MONTHS = array('كانون الثاني','شباط','آذار','نيسان','أيار','حزيران','تموز','آب','أيلول','تشرين الأول','تشرين الثاني','كانون الأول');
$DAYS = array('الأحد','الاثنين','الثلاثاء','الأربعاء','الخميس','الجمعة','السبت');
$dName = date("w"); // the number of the week-day ((from 0 to 6)). [0] for Sunday, [6] for Saturday //
$dm = date("d"); // day of the month in numbers without leading zero; i.e.: 1, 2, 3... 28, 29, 30 //
$mnth = date("n")-1; // number of the month ((from 1 to 12)) this is why we minus 1 from it so that it align with our $MONTHS array.;
$yr = date('Y'); // four-digit year; eg.: 1981 //
return $DAYS[$dName] . " " . $dm . " / " . $MONTHS[$mnth] . " / " . $yr;
}
$today = arDate();
echo $today; // الأحد 01 / آب / 2021
?>
EXPLANATION:
We first prepare two arrays with arabic names of both the days and months. Then we get four variables using the PHP built-in function date(). This function has lots of parameters to control its return. I'm here using the parameters that would give me numbers so that I use them as indexes in the $MONTHS[bla bla bla] and $DAYS[bla bla bla] vars. Finally, format your arabic date to your heart content!
have a look at PHP date() function in here
NOTE1:
Do notice, please, that you can play with the arrangement of the days and months so that you don't need to minus one from your variables (-1) as I did above. Refer to the link of W3S and you would understand how to organize your arabic-name ARRAYS.
NOTE2:
Also, notice please that I'm using the Classical Arabic names in my function and which are used in Syria only; they are not so well-known in the rest of the Arab-league states though they are the classical names for months in Arabic.
Have you run
locale -a
and verified that your system has a locale called "ar"? It might be called something more specific, e.g. "ar_AR.utf8"... If you need to support Arabic locale spelled differently in multiple systems, you may pass an array to setlocale(). The first locale name in that array that the system supports will be used.
I use this javascript function if i can help:
<script type='text/javascript'>
navig = navigator.appName;
versn = parseInt(navigator.appVersion);
if ( (navig == "Netscape" && versn >= 3) || (navig == "Microsoft Internet Explorer" && versn >= 4))
info = "true";
else info = "false";
function Ar_Date() {
if (info == "true") {
var info3 = new Date();
var info4=info3.getDay();
var info5=info3.getMonth();
var info6=info3.getDate();
var info7=info3.getFullYear();
var info8 = new Array('لأحد','الإثنين','الثلاثاء','الأربعاء','الخميس','الجمعة','السبت');
var info9 = info8[info4];
var info10 = new Array('جانفي','فيفري','مارس','أفريل','ماي','جوان','جويلية','أوت','سبتمبر','أكتوبر','نوفمبر','ديسمبر');
var info11 = info10[info5];
var info12=info9+'، '+info6+' '+info11+' '+info7;
var info12=info9+'، '+info6+' '+info11;
document.write(info12);
}
}
</script>
function single_post_arabic_date($postdate_d,$postdate_d2,$postdate_m,$postdate_y) {
$months = array("01" => "يناير", "02" => "فبراير", "03" => "مارس", "04" => "أبريل", "05" => "مايو", "06" => "يونيو", "07" => "يوليو", "08" => "أغسطس", "09" => "سبتمبر", "10" => "أكتوبر", "11" => "نوفمبر", "12" => "ديسمبر");
$ar_month =months[$postdate_m];
$find = array ("Sat", "Sun", "Mon", "Tue", "Wed" , "Thu", "Fri");
$replace = array ("السبت", "الأحد", "الإثنين", "الثلاثاء", "الأربعاء", "الخميس", "الجمعة");
$ar_day_format = $postdate_d2;
$ar_day = str_replace($find, $replace, $ar_day_format);
header('Content-Type: text/html; charset=utf-8');
$standard = array("0","1","2","3","4","5","6","7","8","9");
$eastern_arabic_symbols = array("٠","١","٢","٣","٤","٥","٦","٧","٨","٩");
$post_date = $ar_day.' '.$postdate_d.' '.$ar_month.' '.$postdate_y;
$arabic_date = str_replace($standard , $eastern_arabic_symbols , $post_date);
return $arabic_date;
}
this is just improve function
<?php
$postdate_d = get_the_date('d');
$postdate_d2 = get_the_date('D');
$postdate_m = get_the_date('m');
$postdate_y = get_the_date('Y');
echo single_post_arabic_date($postdate_d,$postdate_d2, $postdate_m, $postdate_y);
?>
This should work:
setLocale(LC_ALL , 'ar_EG.utf-8');
If dates are still not displayed in Arabic, Then the arabic locale may not be installed on the system, To check it,connect using a terminal and type: locale -a, it would display the installed locales, if Arabic is not listed, you have to install it first and then it should work.
/**
* Convert time string to arabic
*#param string $time
*/
public function arabicDate($time)
{
$en_data = ['January', 'Jan', 'Feburary', 'Feb', 'March', 'Mar',
'April', 'Apr', 'May', 'June', 'Jun',
'July', 'Jul', 'August', 'Aug', 'September', 'Sep',
'October', 'Oct', 'November', 'Nov', 'December', 'Dec',
'Satureday', 'Sat', 'Sunday', 'Sun', 'Monday', 'Mon',
'Tuesday', 'Tue', 'Wednesday', 'Wed', 'Thursday', 'Thu', 'Friday', 'Fri',
'AM', 'am', 'PM', 'pm'
];
$ar_data = ['يناير', 'يناير', 'فبراير', 'فبراير', 'مارس', 'مارس',
'أبريل', 'أبريل', 'مايو', 'مايو', 'يونيو', 'يونيو',
'يوليو', 'يوليو', 'أغسطس', 'أغسطس', 'سبتمبر', 'سبتمبر',
'أكتوبر', 'أكتوبر', 'نوفمبر', 'نوفمبر', 'ديسمبر', 'ديسمبر',
'السبت', 'السبت', 'الأحد', 'الأحد', 'الإثنين', 'الإثنين',
'الثلاثاء', 'الثلاثاء', 'الأربعاء', 'الأربعاء', 'الخميس', 'الخميس', 'الجمعة', 'الجمعة',
'صباحاً', 'صباحاً', 'مساءً', 'مساءً'
];
return str_replace($en_data, $ar_data, $time);
}
<?php
$date = '21 Dec 22 14:13';
$date_time = new DateTime($date);
$formatter = new IntlDateFormatter('ar_DZ',);
print $formatter->format($date_time);
For more reference refer this link.
Does this work for you:
setlocale(LC_ALL,'ar');
echo strftime('%A %d %B %Y');
Hope it helps

Categories