Add Case Switch To PHP Array() - php

PHP SCRIPT:
header('Content-Type: application/json');
$Y = 2017;
$UK_Holidays = array(
'New Year\'s Day' => array(
'start' => strtotime('30-12-'.$Y.' 00:00:00'),
'end' => strtotime('30-12-'.$Y.' 23:59:59'),
'type' => 'Bank holiday',
'Observed' => 'Default'
),
'2nd January (substitute day)' => array(
'start' => '',
'end' => '',
'type' => 'Local holiday',
'Observed' => 'Scotland'
),
);
echo json_encode($UK_Holidays, JSON_PRETTY_PRINT);
OUTPUT:
{
"New Year's Day": {
"start": 1514592000,
"end": 1514678399,
"type": "Bank holiday",
"Observed": "Default"
},
"2nd January (substitute day)": {
"start": "",
"end": "",
"type": "Local holiday",
"Observed": "Scotland"
}
}
MORE INFORMATION:
I have a lot more holidays to implement into this PHP script, some of which are dependant on the day another holiday lands on. For 2nd January (substitute day), I've developed a switch case;
PHP Case Switch For 2nd January (substitute day):
function calculateBankHolidays($Y) {
$bankHols = Array();
switch (date("w", strtotime("01-01-$Y 00:00:00"))) {
case 6:
$bankHols[] = "03-01-$Y";
break;
case 0:
$bankHols[] = "02-01-$Y";
break;
default:
$bankHols[] = "01-01-$Y";
}
return $bankHols;
}
Outputs:
[
{
"New Year's": {
"Start Date": "02-01-2017"
}
}
]
QUESTION:
What is the best way to implement my case switch into my PHP Script?

strtotime is your friend here, combined with the relative formats (see http://php.net/manual/en/datetime.formats.relative.php). You can do things like.
$year = date('Y');
$ts_Jan1 = strtotime("Jan 1 $year -1 day next weekday");
$ts_Jan2 = strtotime("next weekday", $ts_Jan1);
$ts2 = strtotime("first Monday Jan $year");
EDIT: Added this PHPfiddle to show working code. The dates generated by this working code match the dates in the table at the link provided by OP: https://www.timeanddate.com/holidays/uk/2nd-january

Related

PHP returning an element from an array

So I have some code that returns all the time in an array like this Open hours today: 9:00- 9:45, 9:55 - 10:20, 10:30 - 11:00 . If we used $formatted_ranges[array_key_first($formatted_ranges)] instead of join, it would return a single element as like this, "Open hours today: 9:00 - 9:45". However we need to return like this,
Open hours today: 9:00 - 11:00.
$start = DateTime::createFromFormat( 'H:i', $range['from'] );
$end = DateTime::createFromFormat( 'H:i', $range['to'] );
$formatted_ranges = array_map( function( $range ) {
return $this->format_time( $range['from'] ).' - '.$this->format_time($range['to'] );
}, $ranges );
return sprintf(
__( 'Open hours today:', 'example' ) . ' <span>%s</span>',
join( ', ', $formatted_ranges )
);
If I understand the input data correctly, you don't need to iterate and reformat every element in the multidimensional array.
Just access the from from the first row and the to from the last row and you're done. Format just those two values if necessary.
Code: (Demo)
$ranges = [
['from' => '9:00', 'to' => '9:45'],
['from' => '9:55', 'to' => '10:20'],
['from' => '10:30', 'to' => '11:00'],
];
if (!isset($ranges[0]['from'], $ranges[0]['to'])) {
throw new Exception('insufficient business hours data');
}
printf(
'Open hours today: %s - %s',
$ranges[0]['from'],
$ranges[array_key_last($ranges)]['to']
);
Output:
Open hours today: 9:00 - 11:00
The originally shared code was not runnable. From the question, I think you want to reformat a time range array to find the beginning and the end of all the ranges.
As long as all the time are represented as 24-hour clock format, this is an example of how it can be done.
<?php
/**
* Convert multiple ranges into a single range.
*
* #param array $ranges
* #return array
*/
function overallRanges(array $ranges): array {
if (sizeof($ranges) === 0) {
throw new \Exception('The provided ranges array is empty');
}
$range = array_reduce($ranges, function ($carry, $current) {
$from = DateTime::createFromFormat('H:i', $current['from']);
$to = DateTime::createFromFormat('H:i', $current['to']);
$carry['from'] = ($from < $carry['from']) ? $from : $carry['from'];
$carry['to'] = ($to > $carry['to']) ? $to : $carry['to'];
return $carry;
},
[
'from' => DateTime::createFromFormat('H:i', $ranges[0]['from']),
'to' => DateTime::createFromFormat('H:i', $ranges[0]['to']),
]
);
return [
'from' => $range['from']->format('G:i'),
'to' => $range['to']->format('G:i'),
];
}
// example use
$ranges = [
['from' => '9:00', 'to' => '9:45'],
['from' => '9:55', 'to' => '10:20'],
['from' => '10:30', 'to' => '11:00'],
];
var_dump(overallRanges($ranges));
The output:
array(2) {
["from"]=>
string(5) "9:00"
["to"]=>
string(5) "11:00"
}
Should be a good enough start for you to reformat into anything.

Get Date Range Of financial Year in php

How can I get the Financial Year date range in PHP like below when I pass year and return date range of every year start and end.
Like Eg.
Input Array = [2017,2018]
Financial Start Month = 04
Output Array =
[
'2017' => [
'start' => '2016-04-01',
'end' => '2017-03-31'
],
'2018' => [
'start' => '2017-04-01',
'end' => '2018-03-31'
]
]
My Effort:-
$year_arr = [2017,2018];
$fn_month = 04;
$date_range_arr = [];
foreach ($year_arr as $key => $value) {
$fn_start_date_year = ($value - 1);
$fn_start_date_month = $fn_month;
$fn_start_date_day = '01';
$fn_start_date_string = $fn_start_date_year.'-'.$fn_start_date_month.'-'.$fn_start_date_day;
$start_date = date('Y-m-d',strtotime($fn_start_date_string));
$fn_end_date_year = ($value);
$fn_end_date_month = (fn_month == 1)?12:(fn_month-1);
$fn_end_date_day = date('t',strtotime($fn_end_date_year.'-'.$fn_end_date_month.'-01'));
$fn_start_date_string = $fn_end_date_year.'-'.$fn_end_date_month.'-'.$fn_end_date_day;
$end_date = date('Y-m-d',strtotime($fn_start_date_string));
$date_range_arr[$value] = [
'start_date' => $start_date,
'end_date' => $end_date
];
}
Above is my effort. It is working perfectly but needs a more robust code.
A good way to manipulate dates in PHP is using the DateTime class. Here's an example of how to get the results you want using it. By using the modify method, we can avoid worries about complications like leap years (see the result for 2016 below).
$year_arr = [2016,2017,2018];
$fn_month = 03;
foreach ($year_arr as $year) {
$end_date = new DateTime($year . '-' . $fn_month . '-01');
$start_date = clone $end_date;
$start_date->modify('-1 year');
$end_date->modify('-1 day');
$date_range_arr[$year] = array('start_date' => $start_date->format('Y-m-d'),
'end_date' => $end_date->format('Y-m-d'));
}
print_r($date_range_arr);
Output:
Array (
[2016] => Array (
[start_date] => 2015-03-01
[end_date] => 2016-02-29
)
[2017] => Array (
[start_date] => 2016-03-01
[end_date] => 2017-02-28
)
[2018] => Array (
[start_date] => 2017-03-01
[end_date] => 2018-02-28
)
)
Demo on 3v4l.org
Maybe this is what you need?
I use strtotime to parse the date strings.
$year_arr = [2017,2018];
$fn_month = 04;
$date_range_arr = [];
foreach($year_arr as $year){
$date_range_arr[$year] =['start' => date("Y-m-d", strtotime($year-1 . "-" .$fn_month . "-01")),
'end' => date("Y-m-d", strtotime($year . "-" .$fn_month . "-01 - 1 day"))];
}
var_dump($date_range_arr);
Output:
array(2) {
[2017]=>
array(2) {
["start"]=>
string(10) "2016-04-01"
["end"]=>
string(10) "2017-03-31"
}
[2018]=>
array(2) {
["start"]=>
string(10) "2017-04-01"
["end"]=>
string(10) "2018-03-31"
}
}
https://3v4l.org/nMUHt
Try this snippet,
function pr($a)
{
echo "<pre>";
print_r($a);
echo "</pre>";
}
$year_arr = [2017, 2018];
$fn_month = 4;
$date_range_arr = [];
foreach ($year_arr as $key => $value) {
$fn_month = str_pad(intval($fn_month),2, 0, STR_PAD_LEFT);
$date = "".($value-1)."-$fn_month-01"; // first day of month
$date_range_arr[$value] = [
'start_date' => $date,
'end_date' => date("Y-m-t", strtotime($date.' 11 months')), // last month minus and last date of month
];
}
pr($date_range_arr);
die;
str_pad - Pad a string to a certain length with another string
Here is working demo.

PHP - Date range by month

I have a date range and I need it to group by month but I want to keep starting day and ending day. So far I have this:
$interval['from'] = '2017-01-02 00:00:00';
$interval['to'] = '2017-02-06 23:59:59';
$start = Carbon::createFromFormat('Y-m-d H:i:s', $interval['from'])->startOfMonth();
$end = Carbon::createFromFormat('Y-m-d H:i:s', $interval['to'])->startOfMonth()->addMonth();
$separate = CarbonInterval::month();
$period = new \DatePeriod($start, $separate, $end);
foreach ($period as $dt) {
dump($dt);
}
But as result I'm getting:
Carbon\Carbon(3) {
date => "2017-01-01 00:00:00.000000" (26)
timezone_type => 3
timezone => "Europe/Prague" (13)
}
Carbon\Carbon(3) {
date => "2017-02-01 00:00:00.000000" (26)
timezone_type => 3
timezone => "Europe/Prague" (13)
}
It is grouped by month but I need to get whole month period, I mean from
2017-01-02 00:00:00 to 2017-01-31 23:59:59
2017-02-01 00:00:00 to 2017-02-06 23:59:59.
Output:
$array = [
0 => [
'from' => '2017-01-02 00:00:00',
'to' => '2017-01-31 23:59:59'
],
1 => [
'from' => '2017-02-01 00:00:00',
'to' => '2017-02-06 23:59:59'
]
];
What is the easiest way to achive it?
Edit: Here is a little bit modified Carbon version of accepted answer, maybe somebody will need it:
$interval['from'] = '2017-01-02 00:00:00';
$interval['to'] = '2017-04-08 23:59:59';
$interval_from = Carbon::createFromFormat('Y-m-d H:i:s', $interval['from']);
$interval_to = Carbon::createFromFormat('Y-m-d H:i:s', $interval['to']);
$result = [];
foreach (range($interval_from->month, $interval_to->month) as $x) {
$to = $interval_from->copy()->endOfMonth();
if ($x == $interval_to->month) {
$result[] = ["from" => $interval_from, "to" => $interval_to];
} else {
$result[] = ["from" => $interval_from, "to" => $to];
}
$interval_from = $to->copy()->addSecond();
}
PHP code demo
Try this solution you can change from one month to another month(not year) and then check. Lengthy solution but hopefully works correctly, putting explaination.
<?php
ini_set('display_errors', 1);
$from=$interval['from'] = '2017-01-02 00:00:00';
$interval['to'] = '2017-03-07 23:59:59';
$month1=date("m", strtotime($interval['from']));
$month2=date("m", strtotime($interval['to']));
$result=array();
foreach(range($month1, $month2) as $x)
{
$dateTimeObj= new DateTime($from);
$dayDifference=($dateTimeObj->format('d')-1);
$dateTimeObj= new DateTime($from);
$dateTimeObj->add(new DateInterval("P1M"));
$dateTimeObj->sub(new DateInterval("P".$dayDifference."DT1S"));
$to= $dateTimeObj->format("Y-m-d H:i:s");
if($x==$month2)
{
$dateTimeObj= new DateTime($interval['to']);
$noOfDays=$dateTimeObj->format("d");
$dateTimeObj->sub(new DateInterval("P".($noOfDays-1)."D"));
$from=$dateTimeObj->format("Y-m-d H:i:s");
$result[]=array("from"=>$from,"to"=>$interval['to']);
}
else
{
$result[]=array("from"=>$from,"to"=>$to);
}
//adding 1 second to $to for next time to be treated as $from
$dateTimeObj= new DateTime($to);
$dateTimeObj->add(new DateInterval("PT1S"));
$from= $dateTimeObj->format("Y-m-d H:i:s");
}
print_r($result);

Compare current time with values in an array true/false

I'd like to define a set of opening hours for a 7 day week. When a visitor visits the web page I'd like to display the current time and day in a specific country (Nevis, Caribbean) and then compare it with a defined set of opening times to show one of two captions 1) Open 2) Closed. Specifically this is what I want to produce:
I'm using this so far to get the current time and set up the array but how do I compare the two?
<?php
function get_timee($country,$city) {
$country = str_replace(' ', '', $country);
$city = str_replace(' ', '', $city);
$geocode_stats = file_get_contents("http://maps.googleapis.com/maps/api/geocode/json?address=$city+$country,&sensor=false");
$output_deals = json_decode($geocode_stats);
$latLng = $output_deals->results[0]->geometry->location;
$lat = $latLng->lat;
$lng = $latLng->lng;
$google_time = file_get_contents("https://maps.googleapis.com/maps/api/timezone/json?location=$lat,$lng&timestamp=1331161200&key=xxx");
$timez = json_decode($google_time);
$d = new DateTime("now", new DateTimeZone($timez->timeZoneId));
return $d->format('H:i');
}
$array = array(
"Monday" => "10:00 - 18:00",
"Tuesday" => "10:00 - 18:00",
"Wednesday" => "10:00 - 18:00",
"Thursday" => "10:00 - 18:00",
"Friday" => "18:00 - 23:00",
"Saturday" => "18:00 - 23:00",
"Sunday" => "Closed"
);
?>
Its <?php echo get_timee("Federation of Saint Kitts and Nevis","Nevis"); ?>. We're currently ...
You can do all this without having to use google anything. I assume you were doing that so that you can work out the time at the clients location. Or maybe because you were not sure what the timezone on your server was set to, or you know it was set to the wrong timezone for you location.
But you can do all this using the core PHP DateTime() and DateTimeZone() classes like this.
Note: I changed the Opening/Closing times array to make it easier to process!
<?php
$opening_times = array(
"Monday" => array('open' => '10:00', 'close' => '18:00'),
"Tuesday" => array('open' => '10:00', 'close' => '18:00'),
"Wednesday" => array('open' => '10:00', 'close' => '18:00'),
"Thursday" => array('open' => '10:00', 'close' => '18:00'),
"Friday" => array('open' => '18:00', 'close' => '23:00'),
"Saturday" => array('open' => '18:00', 'close' => '23:00'),
"Sunday" => "Closed"
);
function AreWeOpen($were_open, $date)
{
$htm = '';
if ( ! is_array($were_open[$date->format('l')])
&& strtolower($were_open[$date->format('l')]) == 'closed' )
{
$htm = 'We are closed all day Sunday';
} else {
if ( $date->format('H:i') >= $were_open[$date->format('l')]['open']
&& $date->format('H:i') <= $were_open[$date->format('l')]['close']
)
{
$htm = 'We are open';
} else {
$htm = 'We are closed';
}
}
return $htm;
}
Now to run/test the above all you do is:
// set date time to NOW
$date = new DateTime(null, new DateTimeZone('America/St_Kitts'));
echo 'Are we open now? Now is ' . $date->format('l H:i') . ' >';
echo AreWeOpen($opening_times, $date);
echo PHP_EOL;
echo 'Are we open at 09:59 Monday > ';
$date = new DateTime('2015/08/17 09:59:00', new DateTimeZone('America/St_Kitts'));
echo AreWeOpen($opening_times, $date);
echo PHP_EOL;
echo 'Are we open at 10:00 Monday > ';
$date = new DateTime('2015/08/17 10:00:00', new DateTimeZone('America/St_Kitts'));
echo AreWeOpen($opening_times, $date);
echo PHP_EOL;
echo 'Are we open at 18:00 Monday > ';
$date = new DateTime('2015/08/18 18:00:00', new DateTimeZone('America/St_Kitts'));
echo AreWeOpen($opening_times, $date);
echo PHP_EOL;
echo 'Are we open at 18:01 Monday > ';
$date = new DateTime('2015/08/18 18:01:00', new DateTimeZone('America/St_Kitts'));
echo AreWeOpen($opening_times, $date);
echo PHP_EOL;
echo 'Are we open at 18:01 Friday > ';
$date = new DateTime('2015/08/21 18:01:00', new DateTimeZone('America/St_Kitts'));
echo AreWeOpen($opening_times, $date);
echo PHP_EOL;
echo 'Are we open on SUNDAY > ';
$date = new DateTime('2015/08/16 18:01:00', new DateTimeZone('America/St_Kitts'));
echo AreWeOpen($opening_times, $date);
And that gives these results:
Are we open now? Now is Monday 07:38 >We are closed
Are we open at 09:59 Monday > We are closed
Are we open at 10:00 Monday > We are open
Are we open at 18:00 Monday > We are open
Are we open at 18:01 Monday > We are closed
Are we open at 18:01 Friday > We are open
Are we open on SUNDAY > We are closed all day Sunday
On outline of a solution:
Calculate a numerical version of your opening times array. This array would be a mapping of day of week to opening hours, indexing the days in the same time DateTime->Format('w') would, starting with 0 for Sunday, etc. Each entry could be null for no opening hours, or an array containing the number of seconds into the day at which the store opens.
Change get_timee to return the DateTime object iteself.
Determine whether the calculated DateTime object falls within the range for the current date. In particular, use (int)$dateTime->format('w') to get the index, then look that up in your numerical array. If the entry is not null, perform the "seconds" calculation for the dateTime item, and determine whether it falls within the range.

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