I'm trying to save a range of dates that will be filled in by the user, via 2 datepickers that were previously translated to Spanish.
The problem is that when I use strtotime()
on the dates it takes the month as the day and vice versa.
Example: I choose day 27 month 05 and year 2017, but the return value is an incorrect date format since the month is 27. If I choose day 01 month 05 year 2017 then it shows in the array as day 05 month 01 and year 2017.
Here are the functions I use to take the dates from the input texts, and to generate the range between the dates
function takedates() {
if(isset($_POST['repS'])){
$dateStart = $_POST['txtdesde'];
$dateEnd = $_POST['txthasta'];
$fechaArray = generafechas($dateStart,$dateEnd);
}
function generafechas($date1,$date2){
$fecharray = array();
if (is_string($date1) === true){
$deit1 = strftime("%d-%m-%Y",strtotime($date1));
}
if (is_string($date2) === true){
$date2 = strftime("%d-%m-%Y",strtotime($date2));
}
do {
$fecharray[] = date("m-d-Y", $date1);
$date1 = strtotime("+1 day", $date1);
} while($date1 <= $date2);
return $fecharray;
}
?>
My question is: How do i fill the array with the dates in the spanish date format?
PS: I've already used setLocale(LC_TIME,'es_ES')
in the file where I'm using these functions, and the input shows the dates like this "dd/mm/yyyy"
strtotime
does not take your locale into consideration when parsing the datetime string. If you use a date separated by slashes it is assumed to be American-style m/d/y
. If you use a date separated by periods (or dashes if the year is four digits), it is assumed to be rest-of-the-world-style (d.m.y
or d-m-Y
). (Note that if you only use a two digit year and use dashes, PHP will try try to parse it as y-m-d
.)
Instead of strtotime
, you should use date-create-from-format
/ DateTime::createFromFormat
to get a DateTime
object, then build your date string from that.
UPDATE BASED ON COMMENTS: In order to get the output you want, you need to use the intl
extension's IntlDateFormatter
class to make the output.
To modify your code above (untested):
function generafechas($date1,$date2){
$fecharray = array();
if (is_string($date1) && is_string($date2)){
// These lines assume the input is formatted `day-month-year`,
// with 2-digit day and month, and 4-digit year.
$date1 = DateTime::createFromFormat('d-m-Y', $date1)
$date2 = DateTime::createFromFormat('d-m-Y', $date2)
} else {
throw new InvalidArgumentException('Must provide two date strings');
}
// Create the formatter
$formatter = IntlDateFormatter::create('es_ES', null, null, null, null, "d 'de' MMMM 'del' yyyy");
do {
// This line prints the first date in the format you chose above
$fecharray[] = $formatter->format($date1);
$date1->add(new DateInterval("P1D")); // `P1D` means "Duration of 1 Day" in the ISO 8601 standard
} while($date1 <= $date2);
return $fecharray;
}
If you provide the Locale along with the data, you can change what format string is used in createFromFormat
as needed.