Customize response when getting data in Laravel with Resource - php
I am obtaining the information of the dates of some classes created, but I need to obtain them by month and show the number of classes registered in that month, I use the Resources to format the response.
These are my tables:
In my class model, I have this relation
public function classDates() {
return $this->hasMany(ClassDate::class, 'class_id');
}
This is my method for get classes:
public function index(Request $request) {
$request->validate(['timezone' => 'string|timezone']);
$userId = $this->validateCookieAndGetAuthUserId();
$userTimeZone = $this->getUserTimezone($userId);
$requestTimeZone = $request->timezone;
$classes = ClassModel::select('id', 'title', 'cuisine_id', 'owner_id', 'language_id',
'duration_class_time', 'class_capacity', 'regular_price', 'status')
->with(['likes' => function($q) use ($userId) {
$q->select('id','likeable_id','liked')
->where('user_id', $userId ? $userId : 0)
->where('liked', 1);
}])
->withCount('ratings')
->withAvg('ratings', 'rate')
->with('pictures:pictureable_id,url', 'cuisine', 'language')
->with(['user.personal:user_id,timezone_id', 'user.personal.timezone:id,name'])
->with(['classDates' => function($q) {
$q->select('id', 'class_id', 'timestamp', 'timezone', 'event_type');
}])
->where('owner_id', $userId);
/*PAGINATION*/
list($count, $data) = $this->paginationService->pagination($classes, $request);
foreach ($data as $class) {
$timezone = null;
if(!is_null($class->user) &&
!is_null($class->user->personal) &&
!is_null($class->user->personal->timezone)
) {
$timezone = $class->user->personal->timezone->name;
} else if(!is_null($this->getUserTimezone($userId))) {
$timezone = $userTimeZone;
}else{
$timezone = $requestTimeZone;
}
$class->timezone = $timezone;
}
return response(['count' => $count, 'classes' => ClassResource::collection($data)], HttpResponse::HTTP_OK);
}
This is my ClassResource:
public function toArray($request)
{
return [
'id' => $this->id,
'is_liked' => $this->likes ? $this->likes->pluck('liked')->first() : null,
'ratings' => $this->ratings_count,
'rating_avg' => $this->ratings_avg_rate,
'title' => $this->title,
'cuisine' => $this->cuisine ? $this->cuisine->key : null,
'language' => $this->language ? $this->language->alias : null,
'owner' => $this->user ? $this->user->first_name : null,
'duration_class_time' => $this->convertToHoursMins($this->duration_class_time),
'class_capacity' => '10/'.$this->class_capacity, //TODO - FIELD SEATS LEFT
'class_price' => $this->regular_price,
'status' => $this->status,
'class_dates' => $this->customClassDates($this->classDates, $this->timezone, $this->duration_class_time),
'timezone_user' => $this->timezone,
'pictures' => $this->pictures ? $this->pictures->pluck('url')->first() : null
];
}
private function customClassDates($classDates, $timezone, $duration) {
foreach ($classDates as $classDate) {
if(!is_null($classDate->timestamp) && !is_null($timezone) && is_numeric($classDate->timestamp)) {
$date = new DateTime("now", new DateTimeZone($timezone));
$date->setTimestamp($classDate->timestamp);
$classDate->date = $date->format('l, d M, Y \a\t g:i A') . ' (' . $date->format('P').')';
$classDate->time = $date->format("g:i A (P)");
$dateEnd = clone $date;
$dateEnd->add(new DateInterval('PT' . $duration . 'M'));
$classDate->timeDuration = $date->format("g:i").' - '.$dateEnd->format("g:i A (P)");
}
}
return $classDates->first();
}
I get the response:
{
"count": 18,
"classes": [
{
"id": 60,
"is_liked": null,
"ratings": 0,
"rating_avg": 0,
"title": "Class New",
"cuisine": "Colombian",
"language": "English",
"owner": "User",
"duration_class_time": "1 hour 0m",
"class_capacity": "10/80",
"class_price": "2.30",
"status": "Draft",
"class_dates": {
"id": 113,
"class_id": 60,
"timestamp": "1675461300",
"timezone": "GMT-06:00",
"event_type": "public",
"date": "Friday, 03 Feb, 2023 at 4:55 PM (-05:00)",
"time": "4:55 PM (-05:00)",
"timeDuration": "4:55 - 5:55 PM (-05:00)"
},
"timezone_user": "America/Bogota",
"pictures": "https://api.app.localhost/storage/images/classes//img2023020320523668286700.jpeg"
},
]
}
But I want to get as follows:
{
"count":18,
"February":[
{
"amountByMonth":5
},
{
"id":113,
"class_id":60,
"timestamp":"1675461300",
"timezone":"GMT-06:00",
"event_type":"public",
"date":"Friday, 03 Feb, 2023 at 4:55 PM (-05:00)",
"time":"4:55 PM (-05:00)",
"timeDuration":"4:55 - 5:55 PM (-05:00)",
"class":{
"class_id":60,
"is_liked":null,
"ratings":0,
"rating_avg":0,
"title":"Class New",
"cuisine":"Colombian",
"language":"English",
"owner":"User",
"duration_class_time":"1 hour 0m",
"class_capacity":"10/80",
"class_price":"2.30",
"status":"Draft",
"timezone_user":"America/Bogota",
"pictures":"https://api.app.localhost/storage/images/classes//img2023020320523668286700.jpeg"
}
},
{
"id":114,
"class_id":60,
"timestamp":"1675461300",
"timezone":"GMT-06:00",
"event_type":"public",
"date":"Friday, 03 Feb, 2023 at 4:55 PM (-05:00)",
"time":"4:55 PM (-05:00)",
"timeDuration":"4:55 - 5:55 PM (-05:00)",
"class":{
"class_id":60,
"is_liked":null,
"ratings":0,
"rating_avg":0,
"title":"Class New",
"cuisine":"Colombian",
"language":"English",
"owner":"User",
"duration_class_time":"1 hour 0m",
"class_capacity":"10/80",
"class_price":"2.30",
"status":"Draft",
"timezone_user":"America/Bogota",
"pictures":"https://api.app.localhost/storage/images/classes//img2023020320523668286700.jpeg"
}
}
],
"March":[
{
"amountByMonth":2
},
{
"id":115,
"class_id":60,
"timestamp":"1675461300",
"timezone":"GMT-06:00",
"event_type":"public",
"date":"Friday, 03 Mar, 2023 at 4:55 PM (-05:00)",
"time":"4:55 PM (-05:00)",
"timeDuration":"4:55 - 5:55 PM (-05:00)",
"class":{
"class_id":61,
"is_liked":null,
"ratings":0,
"rating_avg":0,
"title":"Class New",
"cuisine":"Colombian",
"language":"English",
"owner":"User",
"duration_class_time":"1 hour 0m",
"class_capacity":"10/80",
"class_price":"2.30",
"status":"Draft",
"timezone_user":"America/Bogota",
"pictures":"https://api.app.localhost/storage/images/classes//img2023020320523668286700.jpeg"
}
},
{
"id":116,
"class_id":61,
"timestamp":"1675461300",
"timezone":"GMT-06:00",
"event_type":"public",
"date":"Friday, 03 Mar, 2023 at 4:55 PM (-05:00)",
"time":"4:55 PM (-05:00)",
"timeDuration":"4:55 - 5:55 PM (-05:00)",
"class":{
"class_id":60,
"is_liked":null,
"ratings":0,
"rating_avg":0,
"title":"Class New",
"cuisine":"Colombian",
"language":"English",
"owner":"User",
"duration_class_time":"1 hour 0m",
"class_capacity":"10/80",
"class_price":"2.30",
"status":"Draft",
"timezone_user":"America/Bogota",
"pictures":"https://api.app.localhost/storage/images/classes//img2023020320523668286700.jpeg"
}
}
]
}
How can I format this in my Resource, or should I modify the initial query. I would like to obtain the records by month, and that would show the number of classes for that month
Related
create a y-m-d.json file in the respective directory (year/month) by iterating multidimensional array
The bounty expires in 7 days. Answers to this question are eligible for a +50 reputation bounty. Cem Firat wants to draw more attention to this question. try to create or update a json file based on the processed data. first I arrange the contents using assamble() and create a multidimensional array: $rawData = [ "AAAA 2022 12 23 21:37:56 dc:16:b2:4c:d2:e6", "BBB 2023 01 12 02:08:23 f0:8a:76:16:57:e8", "BBB 2023 02 19 17:34:33 a0:c9:a0:b6:79:3c", "AAAA 2023 02 23 12:21:09 f0:8a:76:16:57:e8", "AAAA 2023 02 23 18:15:10 f0:8a:76:16:57:e8", "CCCCC 2023 03 19 17:07:26 f0:8a:76:16:57:e8", "QQQ 2023 04 01 00:00:03 a0:c9:a0:b6:79:3c" ]; function dirMaker($a, $b, $c) { if (!is_dir($a . $b . $c)) { mkdir( $a . $b . $c, 0777, true // If true, then any parent directories // to the directory specified will also be created, // with the same permissions. ); } } $archive = 'archive/'; assemble data function assemble() { global $rawData, $dailyData; foreach ($rawData as $row) { [$group, $y, $m, $d, $t, $id] = explode(' ', $row); $result[$y][$m][$d][$group]['user'][$id][] = $t; $years[] = $y; $months[] = $m; $days[] = $d; } $dailyData = $result; } assemble(); result array ( 2022 => array ( 12 => array ( 23 => array ( 'AAAA' => array ( 'user' => array ( 'dc:16:b2:4c:d2:e6' => array ( 0 => '21:37:56', ), ), ), ), ), ), 2023 => array ( '01' => array ( 12 => array ( 'BBB' => array ( 'user' => array ( 'f0:8a:76:16:57:e8' => array ( 0 => '02:08:23', ), ), ), ), ), /... And now comes the big challenge: create a y-m-d.json file in the respective directory (year/month) by iterating multidimensional array In json files the year, month and day should not be omitted. But put in the correct year/month directory with which json filenames (y-m-d.json) are written. function archiveJSON() { global $y, $m, $d, $archive, $dailyData, $rawData; foreach ($rawData as $year) { [$group, $y, $m, $d, $t, $id] = explode(' ', $year); dirMaker($archive, $y . '/', $m . '/'); $p = $archive . $y . '/' . $m . '/'; $f = $y . '-' . $m . '-' . $d . '.json'; if (!file_exists($p . $f)) { // Create a new json file in current date directory // and write data fopen($p . $f, 'w'); file_put_contents($p . $f, json_encode($dailyData[$y][$m][$d], JSON_PRETTY_PRINT)); } else { # Existing Data $existingtJSON = file_get_contents($p . $f); $existingtArr = json_decode($existingtJSON, true); foreach ($dailyData as $letter => $set) { if (!isset($existingtArr[$letter])) { $existingtArr[$letter] = $set; } else { $existingtArr[$letter]['user'] = array_merge_recursive( $existingtArr[$letter]['user'], $set['user'] ); } } // update file file_put_contents($p . $f, json_encode($dailyData, JSON_PRETTY_PRINT)); } } } archiveJSON(); yes! if the directories (year/month) do not exist, they will be created if (!file_exists($p . $f)): 2022/12, 2023/1,2,3,4 and the json files with the right names (Y-m-d.json) in the right directory too. for the 1st i'm stuck here: but if one of the letters has 2 entries on the same date as in this example: AAAA 2023 02 23 12:21:09 ... and AAAA 2023 02 23 18:15:10 ... then the 2023-02-23.json file all year entries written: { "2022": { "12": { "23": { "AAAA": { "user": { "dc:16:b2:4c:d2:e6": [ "21:37:56" ] } } } } }, "2023": { "01": { "12": { "BBB": { "user": { "f0:8a:76:16:57:e8": [ "02:08:23" ] } } } }, "02": { "19": { "BBB": { "user": { "a0:c9:a0:b6:79:3c": [ "17:34:33" ] } } }, "23": { "AAAA": { "user": { "f0:8a:76:16:57:e8": [ "12:21:09", "18:15:10" ] } } } }, "03": { "19": { "CCCCC": { "user": { "f0:8a:76:16:57:e8": [ "17:07:26" ] } } } }, "04": { "01": { "QQQ": { "user": { "a0:c9:a0:b6:79:3c": [ "00:00:03" ] } } } } } } else: if there are json data in the right directory with the right files, then complete them with the new entries: secondly, I'm stuck here as well: as above, all entries are written in each of the json files. I would have to put $dailyData[$y][$m][$d] in the right place. Or am I misunderstanding something? i try many hours around. I spin around in circles. Please don't be too harsh with me, because I'm an ambitious beginner and my head is getting tired.
Laravel: Count integer value inside array from JSON
I'm trying to count integer value from JSON: https://pomber.github.io/covid19/timeseries.json but I got 1 for each key. What I expect is to count the total 'confirmed' from all countries by date as a key. Here's my controller: $client = new Client();$request = $client->get('https://pomber.github.io/covid19/timeseries.json'); $response = $request->getBody()->getContents(); $posts_dates = json_decode($response, true); $confirmed_array = array(); if ( ! empty( $posts_dates ) ) { foreach ( $posts_dates as $key => $val ) { foreach ( ((array)$posts_dates)[$key] as $data ) { $date_confirmed = new \DateTime( $data['date'] ); $day = $date_confirmed->format( 'd M y' ); $confirmed = count((array)$data['confirmed']); $confirmed_array [ $day ] = $confirmed; } } } return $confirmed_array; Here's the result: { "22 Jan 20": 1, "23 Jan 20": 1, "24 Jan 20": 1, "25 Jan 20": 1, "26 Jan 20": 1, "27 Jan 20": 1, "28 Jan 20": 1, "29 Jan 20": 1, "30 Jan 20": 1, "31 Jan 20": 1, .... } UPDATE I want to get the output to looks like below: { "date": [ "22 Jan 20", "23 Jan 20", "24 Jan 20", "25 Jan 20", ..... ], "total_confirmed": [ 555, 653, 941, 1434, ..... ], "max_value_of_total_confirmed": 12214 } Any help would be appreciated :)
This code just loops through each countries data and then for each date it adds the data to the result array... foreach ( $posts_dates as $country => $data ) { foreach ( $data as $date => $dateData ) { if ( !isset($confirmed_array[$dateData['date']]) ) { $confirmed_array[$dateData['date']] = 0; } $confirmed_array[$dateData['date']] += $dateData['confirmed']; } } Update: For the new format, you just need to extract the data from the array so far... $output = ["date" => array_keys($confirmed_array), "total_confirmed" => array_values($confirmed_array), "max_value_of_total_confirmed" => max($confirmed_array) ];
Add Case Switch To PHP Array()
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
Sort array in chronological order with date as key -php
I basically have this code which determines the number of same dates in an array: function get_archives_html ($blog) { //tag array to store arrays with same tag $count_tags = array(); //store output $output = ''; foreach($blog as $id) { //abbreviate date name $originalDate = $id["date"]["year"].'-'.$id["date"]["month"].'-'.$id["date"]["day"]; $abbrevDate = date("F, Y", strtotime($originalDate)); if(!isset($count_tags[$abbrevDate])) { $count_tags[$abbrevDate] = 0; } ++$count_tags[$abbrevDate]; } // Sort your tags from hi to low //arsort($count_tags); var_dump($count_tags); foreach($count_tags as $month=>$id) { $output.= '<p>'. $month.($id > 1 ? ' ('.$id .')' : '').'</p>'; } return $output; } The output would look like this: $arr = array( "November, 2016" => "2", "October, 2016" => "5", "October, 2017" => "3", "September, 2017" => "6" ); Now, I use the keys to display it on the html. Problem is that it is not arranged properly by date but rather by alphabet. So, my question is, how can I sort this array by key and by date. Example would be October, 2016, November 2016, September, 2017, October 2014 Thank you
<?php $arr = array( "November, 2016" => "2", "October, 2016" => "5", "October, 2017" => "3", "September, 2017" => "6" ); //Sort by ascending date in the key uksort($arr,function($a,$b){ return strtotime(strtr($a,',',' '))<=>strtotime(strtr($b,',',' ')); }); //result $expected = array ( 'October, 2016' => "5", 'November, 2016' => "2", 'September, 2017' => "6", 'October, 2017' => "3", ); var_dump($arr === $expected); //bool(true)
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