How to display PHP date in Turkish? - php

How can I display the date in Turkish language?
I'm trying following code but it does not print anything at all.
setlocale(LC_ALL, 'tr_TR.UTF-8');
echo strftime("%e %B %Y %A", time());

Though i don't understand turkish but it is printing output
14 Şubat 2013 Perşembe
So your code is fine.
Hope you are not missing out php tags. :/

<?php
setlocale(LC_ALL, 'tr_TR.UTF-8');
echo strftime("%e %B %Y %A", time());
?>
Prints out: 30 Ekim 2015 Cuma
Code works fine.

Php date for "F" which gives month of English name to translate to Turkish given example
date("d F")
you can use this function
function convertMonthToTurkishCharacter($date){
$aylar = array(
'January' => 'Ocak',
'February' => 'Şubat',
'March' => 'Mart',
'April' => 'Nisan',
'May' => 'Mayıs',
'June' => 'Haziran',
'July' => 'Temmuz',
'August' => 'Ağustos',
'September' => 'Eylül',
'October' => 'Ekim',
'November' => 'Kasım',
'December' => 'Aralık',
'Monday' => 'Pazartesi',
'Tuesday' => 'Salı',
'Wednesday' => 'Çarşamba',
'Thursday' => 'Perşembe',
'Friday' => 'Cuma',
'Saturday' => 'Cumartesi',
'Sunday' => 'Pazar',
'Jan' => 'Oca',
'Feb' => 'Şub',
'Mar' => 'Mar',
'Apr' => 'Nis',
'May' => 'May',
'Jun' => 'Haz',
'Jul' => 'Tem',
'Aug' => 'Ağu',
'Sep' => 'Eyl',
'Oct' => 'Eki',
'Nov' => 'Kas',
'Dec' => 'Ara'
);
return strtr($date, $aylar);
}

add it before the code.
setlocale (LC_ALL, 'tr_TR.UTF-8', 'tr_TR', 'tr', 'turkish');

public function getTurkishDate(){
$locale = 'tr_TR'; // a canonicalized locale
$format = 'dd-MMMM-YYYY'; // ISO format codes, not the typical date ones
$dt = new DateTime(); // a DateTime object
$df = new IntlDateFormatter(
$locale, // string locale
IntlDateFormatter::NONE, // int date type
IntlDateFormatter::NONE, // int time type
'UTC', // string timezone
IntlDateFormatter::GREGORIAN, // int cal type
$format // string pattern
);
return $df->format($dt); //string 07-Ağustos-2018
}
OR
public function getTurkishDate(){
$locale = 'tr_TR'; // a canonicalized locale
$format = 'dd-MMMM-YYYY-EEEE'; // ISO format codes, not the typical date ones
$dt = new DateTime(); // a DateTime object
$df = new IntlDateFormatter(
$locale, // string locale
IntlDateFormatter::NONE, // int date type
IntlDateFormatter::NONE, // int time type
'UTC', // string timezone
IntlDateFormatter::GREGORIAN, // int cal type
$format // string pattern);
return $df->format($dt); //string 07-Ağustos-2018-Salı
}
OR
public function getTurkishDate(){
$locale = 'tr_TR'; // a canonicalized locale
$format = 'dd-MMMM-YYYY-ee'; // ISO format codes, not the typical date ones
$dt = new DateTime(); // a DateTime object
$df = new IntlDateFormatter(
$locale, // string locale
IntlDateFormatter::NONE, // int date type
IntlDateFormatter::NONE, // int time type
'UTC', // string timezone
IntlDateFormatter::GREGORIAN, // int cal type
$format // string pattern);
return $df->format($dt); //string 07-Ağustos-2018-02
}

You can take current date and time with:
<?php
date_default_timezone_set("Europe/Istanbul");
//echo "The time is " . date("H:i") . "<br>";
//echo "Today is " . date("Y-m-d") . "<br>";
//echo "Today is " . date("l");
$now_time = date("H:i");
$now_date = date("Y-m-d");
?>

Related

Is there a fast way to convert date to spanish?

With this:
date( 'd F Y', strtotime( $row["datestart"] ) )
I get this:
08 July 2016
But I need to get this:
08 Julio 2016
Julio is July in spanish.
I have added this to the top of the php page:
setlocale(LC_TIME, 'es_ES');
but it doesn't work.
So what can I do ?
This worked for me:
setlocale(LC_TIME, 'es_ES', 'Spanish_Spain', 'Spanish');
$date = str_replace("/","-","08/07/2016");
echo strftime('%d %B %Y',strtotime($date)); // 08 julio 2016
setlocale is the key ingredient here.
update: PHP 8.x
$format = new IntlDateFormatter('es_ES', IntlDateFormatter::SHORT, IntlDateFormatter::NONE, NULL, NULL, 'dd MMMM y');
echo $format->format(new DateTime('now', new DateTimeZone('UTC')));
Use format to output the DateTime to the locale you specify in IntlDateFormatter (DateTimeZone is optional).
Another variant you may use:
Install intl extension for php (link).
Enable it in your php.ini file and then you will be able to check it is working with the following sample:
$f = new IntlDateFormatter('es_ES', null, null, null, null, null, 'dd MMMM y');
print($f->format(new DateTime('2016-07-08'));
An expected output will be the following:
08 julio 2016
You could make an associative array.
Set the keys to the months in English and the values to the corresponding months in Spanish.
It would look something like this...
$months = array(
'january' => 'enero',
'february' => 'febrero',
'march' => 'marzo',
'april' => 'abril',
'may' => 'mayo',
'june' => 'junio',
'july' -> 'julio',
'august' => 'agosto',
'september' => 'septiembre',
'october' => 'octubre',
'november' => 'noviembre',
'december' => 'diciembre'
);
Then you could reference the months like this...
$enMonth = "july"; //This is the month in English that you will match to the corresponding month in Spanish.
$esMonth = $months[$enMonth]; //You are returning the value (which is Spanish) of the key (which is English), giving you the month in Spanish.
You could probably also use Google Translate's API, but it seems like too much for something that can be done with a simple array.
Here is Google Translate's API if you are interested in translating other words, or a larger array of words.

Converting birthday in format DDMMMYY to date value in PHP

I've got bunch of birthdays which are stored in format DDMMMYY. I need to convert those to date values, so i can store those in database.
Is there any easy way of telling strtotime function that date must be in the past?
<?php
$datestring = '22SEP41';
echo date('Y-m-d',strtotime($datestring)); //outputs 2041-09-22, should be 1941-09-22
?>
<?php
$datestring = '22SEP41';
$matches = [];
preg_match('/([0-9]{2})([A-Z]{3})([0-9]{2})/', $datestring, $matches);
$prefix = ($matches[3] <= date('y') ? '20' : '19');
$matches[3] = "{$prefix}{$matches[3]}";
$ts = strtotime("{$matches[1]} {$matches[2]} {$matches[3]}");
// date ('Y-m-d', $ts) == 1941-09-22
This assumes that 22SEP06 should be interpreted as 2006 rather than 1906 - basically it gives the output a range of 1917 -> 2016.
This method create a date of past century only if standard evaluated date is after today:
$date = date_create( $datestring );
if( $date->diff( date_create() )->invert )
{
$date->modify( '-100 years' );
}
echo $date->format( 'Y-m-d' );
For
$datestring = '22SEP41';
the output is:
1941-09-22
For
$datestring = '22SEP01';
the output is:
2001-09-22
eval.in demo
Basically, we create a DateTime based on given string, then we calculate difference with current day; if the difference is negative (->invert), we subtract 1 century from the date.
You can personalize the condition using ->format('%R%Y') instead of ->invert. In this example:
if( $date->diff( date_create() )->format('%R%Y') < 10 )
Dates from 00 through 05 as evaluated as 2000-2005.
You could try something like:
$ds = '22SEP41';
$day = $ds[0].$ds[1];
// Getting the month.
$mon = array(
'JAN' => 1,
'FEB' => 2,
'MAR' => 3,
'APR' => 4,
'MAY' => 5,
'JUN' => 6,
'JUL' => 7,
'AUG' => 8,
'SEP' => 9,
'OCT' => 10,
'NOV' => 11,
'DEC' => 12
);
$mont = $ds[2].$ds[3].$ds[4];
$month = $mon[$mont]; // Gets the month real.
$year = '19'.$ds[5].$ds[6];
$final = $day.'-'.$month.'-'.$year;
I tested it on my local machine and it worked. Hope it works and is what you're looking for :)

Right timezone for timestamp

The code below would set open and closed on my website. But it is not in the right time zone. How do i set it to the Dutch time zone?
So can some one help me out.
And also i have a question about setting it in days.
So you can set on the website the shippingtime depending on day. So on monday the shipping time is: send today. Or on sunday it is send on monday.
<?php
/**
* Based on the following business hours:
* (Note : I setup the hours for each day if they carry-over)
* everyday is open from 09:00 AM - 12:00 AM
* Sun/Sat open extra from 12:00 AM - 01:00 AM
*/
$storeSchedule = [
'Sun' => ['00:00 AM' => '00:00 AM'],
'Mon' => ['9:00 AM' => '00:00 PM'],
'Tue' => ['9:00 AM' => '05:00 PM'],
'Wed' => ['9:00 AM' => '05:00 PM'],
'Thu' => ['9:00 AM' => '05:00 PM'],
'Fri' => ['9:00 AM' => '05:30 PM'],
'Sat' => ['9:00 AM' => '04:30 PM']
];
// current OR user supplied UNIX timestamp
$timestamp = time();
// default status
$status = 'momenteel gesloten, stuur ons een mail';
// get current time object
$currentTime = (new DateTime())->setTimestamp($timestamp);
// loop through time ranges for current day
foreach ($storeSchedule[date('D', $timestamp)] as $startTime => $endTime) {
// create time objects from start/end times
$startTime = DateTime::createFromFormat('h:i A', $startTime);
$endTime = DateTime::createFromFormat('h:i A', $endTime);
// check if current time is within a range
if (($startTime < $currentTime) && ($currentTime < $endTime)) {
$status = '<b>bereikbaar op: Tel: 023-5313188</b> of <b>mail</b>';
break;
}
}
echo "Onze klantenservice is $status";
?>
use this for instantiating the current DateTime Object in Dutch Timezone:
$current = new DateTime(
'now',
new DateTimeZone('Europe/Amsterdam')
);
the problem was at the DateTime comparison. Creating a DateTime object from only the time sets the date to 1970-01-01...
/**
* Based on the following business hours:
* (Note : I setup the hours for each day if they carry-over)
* everyday is open from 09:00 AM - 12:00 AM
* Sun/Sat open extra from 12:00 AM - 01:00 AM
*/
$storeSchedule = [
'Sun' => ['00:00 AM' => '00:00 AM'],
'Mon' => ['9:00 AM' => '00:00 PM'],
'Tue' => ['9:00 AM' => '05:00 PM'],
'Wed' => ['9:00 AM' => '05:00 PM'],
'Thu' => ['9:00 AM' => '05:00 PM'],
'Fri' => ['9:00 AM' => '05:30 PM'],
'Sat' => ['9:00 AM' => '04:30 PM']
];
// current OR user supplied UNIX timestamp
$timestamp = '2015-03-12 12:00:00'; // shows it is open
//$timestamp = '2015-03-12 8:59:59'; // shows closed
//$timestamp = '2015-03-12 9:00:00'; // shows open
//$timestamp = 'now'; // shows current status
// default status
$status = 'momenteel gesloten, stuur ons een mail';
// default timezone
$timeZone = new DateTimeZone('Europe/Amsterdam');
// get current time object
$currentTime = new DateTime($timestamp, $timeZone);
// loop through time ranges for current day
foreach ($storeSchedule[date('D', $timestamp)] as $startTime => $endTime) {
// create time objects from start/end times
$startTime = DateTime::createFromFormat(
'Y-m-d h:i A',
$currentTime->format('Y-m-d') . ' ' . $startTime,
$timeZone
);
$endTime = DateTime::createFromFormat(
'Y-m-d h:i A',
$currentTime->format('Y-m-d') . ' ' . $endTime,
$timeZone
);
// check if current time is within a range
if (($startTime <= $currentTime) && ($currentTime <= $endTime)) {
$status = '<b>bereikbaar op: Tel: 023-5313188</b> of <b>mail</b>';
break;
}
}
echo "Onze klantenservice is $status";

Date and time stored on variables don't refresh while page

Date and time are setted to Madrid's standard UTC, and stored for translation and formatting in this way:
date_default_timezone_set('Europe/Madrid');
$dia=""; $mes=""; $dia2=""; $ano=""; $horaActual=""; $minutoActual="";
$dia=date("l");
if ($dia=="Monday") {$dia="Lunes";} if ($dia=="Tuesday") {$dia="Martes";} if ($dia=="Wednesday") {$dia="Miércoles";} if ($dia=="Thursday") {$dia="Jueves";} if ($dia=="Friday") {$dia="Viernes";} if ($dia=="Saturday") {$dia="Sabado";} if ($dia=="Sunday") {$dia="Domingo";}
$mes=date("F");
if ($mes=="January") {$mes="Enero";} if ($mes=="February") {$mes="Febrero";} if ($mes=="March") {$mes="Marzo";} if ($mes=="April") {$mes="Abril";} if ($mes=="May") {$mes="Mayo";} if ($mes=="June") {$mes="Junio";} if ($mes=="July") {$mes="Julio";} if ($mes=="August") {$mes="Agosto";} if ($mes=="September") {$mes="Setiembre";} if ($mes=="October") {$mes="Octubre";} if ($mes=="November") {$mes="Noviembre";} if ($mes=="December") {$mes="Diciembre";}
$dia2=date("d");
$ano=date("Y");
$horaActual=date("H");
$minutoActual=date("m");
This gives the same time and date all the time (I created this an hour ago), not refreshing while web browser does. In this right moment, this code:
<?php echo "$dia $dia2 de $mes, $horaActual:$minutoActual"; echo "--" date("F j, Y, g:i a");?>
Shows:
Lunes 26 de Mayo, 16:05 -- May 26, 2014, 5:03 pm
So date() is getting the correct and updated info, but variables are not updating this info, showing stucked data from the first time they stored this values.
every time user gets inside this url, date and time must be updated with actual values
I dont know how your time got stuck, but alternatively you could do this (time updated). Consider this example:
date_default_timezone_set('Europe/Madrid');
$dia = $mes = $dia2 = $ano = $horaActual = $minutoActual = "";
$days = array('Monday' => 'Lunes', 'Tuesday' => 'Martes', 'Wednesday' => 'Miércoles', 'Thursday' => 'Jueves', 'Friday' => 'Viernes', 'Saturday' => 'Sabado', 'Sunday' => 'Domingo');
$months = array('January' => 'Enero', 'February' => 'Febrero', 'March' => 'Marzo', 'April' => 'Abril', 'May' => 'Mayo', 'June' => 'Junio', 'July' => 'Julio', 'August' => 'Agosto', 'September' => 'Setiembre', 'October' => 'Octube', 'November' => 'Noviembre', 'December' => 'Diciembre');
$dia = date("l");
$mes = date("F");
$dia2 = date("d");
$ano = date("Y");
// $horaActual = date("H");
// $minutoActual = date("m");
$time = date('H:i');
echo "$days[$dia] $dia2 de $months[$mes], $time"; echo "--". date("F j, Y, g:i a");
// outputs: Lunes 26 de Mayo, 17:21--May 26, 2014, 5:21 pm
Fiddle

DateTime "first day of last month" not returning the first day

I looked at this answer already, and it's quite close to what I have.
Here is my PHP code:
$start = new DateTime('0:00 first day of previous month', new DateTimeZone('UTC'));
/*
if (isset($_GET['year']) && isset($_GET['month']) && checkdate($_GET['month'], 1, $_GET['year'])) {
$start = DateTime::createFromFormat('Y-m-d', $_GET['year'] . '-' . $_GET['month'] . '-1');
}*/
$middle = DateTime::createFromFormat('U', strtotime('first day of last month', $start->format('U')));
$middle->setTimezone(new DateTimeZone('UTC'));
$end = DateTime::createFromFormat('U', strtotime('first day of 2 months ago', $start->format('U')));
$end->setTimezone(new DateTimeZone('UTC'));
var_dump($start);
var_dump($middle);
var_dump($end);
Today is August 27th, so I would expect July 1, June 1, and May 1. Here's what the actual output is:
object(DateTime)[1]
public 'date' => string '2013-07-01 00:00:00' (length=19)
public 'timezone_type' => int 3
public 'timezone' => string 'UTC' (length=3)
object(DateTime)[2]
public 'date' => string '2013-05-02 00:00:00' (length=19)
public 'timezone_type' => int 3
public 'timezone' => string 'UTC' (length=3)
object(DateTime)[3]
public 'date' => string '2013-04-02 00:00:00' (length=19)
public 'timezone_type' => int 3
public 'timezone' => string 'UTC' (length=3)
Why is it returning the second day of the months for me?
I've also tried it without the new DateTimeZone('GMT') as the second parameter of the constructor for the initial DateTime but it still gives me the same result, just with different times.
this part irrelevant - question was edited
Because of the timezone difference. $start is calculated in the 'Rainy River timezone', while $middle and $end are in UTC time.
The 'Rainy River timezone has a -06:00 hour offset from UTC (exactly the difference in hours between the first with the second and third results).
update 1 - solution
It seems the problem lies somewhere around strtotime. For some reason it yields a result with an offset of one day (further explanation needed). A simple solution, is to subtract one second from that date and it will produce the correct result.
$timezone = new DateTimeZone('UTC');
$start = new DateTime('0:00 first day of previous month', $timezone );
$middle = DateTime::createFromFormat('U', strtotime('first day of last month',($start ->format('U'))-1),$timezone);
echo $middle->format('Y-m-d')."\n";
Result:
2013-05-01
update 2 - reason for problem
Eventually I find out that the problem originates from the instantiation of the fisrt date object. Here is an illustration.
This will give a correct result:
$original = new DateTime('2013-05-01');
echo $original->format('Y-m-d')."\n";
$previous= DateTime::createFromFormat('U', strtotime('first day of last month',($original->format('U'))),new DateTimeZone('UTC'));
echo $previous->format('Y-m-d')."\n";
Result (OK):
2013-05-01
2013-04-01 <--- OK
However, this will not (only first line different, as in the original code):
$original = new DateTime('0:00 first day of previous month', new DateTimeZone('UTC'));
echo $original->format('Y-m-d')."\n";
$previous= DateTime::createFromFormat('U', strtotime('first day of last month',($original->format('U'))),new DateTimeZone('UTC'));
echo $previous->format('Y-m-d')."\n";
Result:
2013-07-01
2013-05-02 <--- BAD
After reading the answer here, I had a better idea:
$start = new DateTime('0:00 first day of previous month');
/*
if (isset($_GET['year']) && isset($_GET['month']) && checkdate($_GET['month'], 1, $_GET['year'])) {
$start = DateTime::createFromFormat('Y-m-d', $_GET['year'] . '-' . $_GET['month'] . '-1');
}*/
$middle = clone $start;
$middle->modify('first day of last month');
$end = clone $start;
$end->modify('first day of 2 months ago');
var_dump($start);
var_dump($middle);
var_dump($end);
Output:
object(DateTime)[1]
public 'date' => string '2013-07-01 00:00:00' (length=19)
public 'timezone_type' => int 3
public 'timezone' => string 'America/Rainy_River' (length=19)
object(DateTime)[2]
public 'date' => string '2013-06-01 00:00:00' (length=19)
public 'timezone_type' => int 3
public 'timezone' => string 'America/Rainy_River' (length=19)
object(DateTime)[3]
public 'date' => string '2013-05-01 00:00:00' (length=19)
public 'timezone_type' => int 3
public 'timezone' => string 'America/Rainy_River' (length=19)
Also, I realize that a DateTimeImmutable would be a better choice for the $start instance (so that I don't have to clone the other two), but I don't have access to PHP 5.5 yet.

Categories