How to display dates in different formats in English and Spanish with PHP


Hello everyone, this time we are going to learn how to make a small function that will help us to show the dates in different formats and also make translations into English or Spanish.

<?php
function now($format, $language = "es") {
 if($format == 1) {
 return ($language === "es") ? date("d/m/y", time()) : date("m/d/y", time());
 } elseif($format == 2) { 
 $day = date("l");

 if ($language === "es") {
 if ($day == "Monday") $day = "Lunes";
 if ($day == "Tuesday") $day = "Martes";
 if ($day == "Wednesday") $day = "Miércoles";
 if ($day == "Thursday") $day = "Jueves";
 if ($day == "Friday") $day = "Viernes";
 if ($day == "Saturday") $day = "Sabado";
 if ($day == "Sunday") $day = "Domingo";
 }

 $day2 = date("d");
 $month = date("F");

 if ($language === "es") {
 if ($month == "January") $month = "Enero";
 if ($month == "February") $month = "Febrero";
 if ($month == "March") $month = "Marzo";
 if ($month == "April") $month = "Abril";
 if ($month == "May") $month = "Mayo";
 if ($month == "June") $month = "Junio";
 if ($month == "July") $month = "Julio";
 if ($month == "August") $month = "Agosto";
 if ($month == "September") $month = "Setiembre";
 if ($month == "October") $month = "Octubre";
 if ($month == "November") $month = "Noviembre";
 if ($month == "December") $month = "Diciembre";
 }

 $year = date("Y"); 

 return ($language === "es") ? "$day, $day2 de $month de $year" : "$month $day2, $year";
 } elseif($format == 3) {
 return ($language === "es") ? date("d-m-Y H:i:s", time()) : date("Y-m-d H:i:s", time());
 }
}
?>

To use it we can simply send it to call in the following way:

<?php
 echo now (1); // Print: 03/27/13 echo now (1, "en"); // Print: 03/27/13 echo now (2); // Print: Wednesday, March 27, 2013 echo now (2, "en"); // Print: March 27, 2013 echo now (3); // Print: 2013-03-27 12:00:00 echo now (3, "en"); // Print: 2013-03-27 12:00:00

I hope this is useful for you, regards!

Previous The 6 trends of 2013 for websites
Next Update Wordpress

No Comment

Leave a reply

Your email address will not be published. Required fields are marked *