PHP equivalent JavaScript functions

0

I have this code in JavaScript, getting the values of some datepicker and it works correctly:

var fecha_ini = $('.fecha_ini').val();
var fecha_ini_dia = fecha_ini.substring(0,2);
var fecha_ini_mes = fecha_ini.substring(3,5);
var fecha_ini_anio = fecha_ini.substring(6,10);

var fecha_fin = $('.fecha_fin').val();
var fecha_fin_dia = fecha_fin.substring(0,2);
var fecha_fin_mes = fecha_fin.substring(3,5);
var fecha_fin_anio = fecha_fin.substring(6,10);

var fecha_ini_horas = new Date(fecha_ini_anio,parseInt(fecha_ini_mes)-1,fecha_ini_dia,0,0,0);
var fecha_fin_horas = new Date(fecha_fin_anio,parseInt(fecha_fin_mes)-1,fecha_fin_dia,0,0,0);

I'm just trying to do the same with PHP code but it does not come out. What would be the equivalent code block in that language?

    
asked by Ivan92 27.03.2018 в 19:07
source

1 answer

2

Assuming that you have already defined your date in a variable or you bring it from a request to your php file by a form or by the url, you can do the following:

$fecha_ini = $_GET['fecha_ini'];
$fecha_ini_dia = substr($fecha_ini,0,2);
$fecha_ini_mes = substr($fecha_ini,3,5);
$fecha_ini_anio = substr($fecha_ini,6,10);

$fecha_fin = $_GET['fecha_fin'];
$fecha_fin_dia = substr($fecha_fin,0,2);
$fecha_fin_mes = substr($fecha_fin,3,5);
$fecha_fin_anio = substr($fecha_fin,6,10);

$delimitador = '-';

$fecha_ini_horas = new DateTime($fecha_ini_anio.$delimitador.$fecha_ini_mes.$delimitador.$fecha_ini_dia);
$fecha_fin_horas = new DateTime($fecha_fin_anio.$delimitador.$fecha_fin_mes.$delimitador.$fecha_fin_dia);

If your date has the format dia-mes-año or año-mes-dia you can directly pass your date, without having to divide it into the parts corresponding to the days, month and year.

$fecha_ini = $_GET['fecha_ini'];
$fecha_fin = $_GET['fecha_fin'];
$fecha_ini_horas = new DateTime(fecha_ini);
$fecha_fin_horas = new DateTime(fecha_fin);

But if you use another delimiter or the order is not the one of day, month, year then you can use the static function createFromFormat of the DateTime class to indicate which format has the string you want to convert. If for example it was month / day / year (12/28/2017)

$fecha_ini = $_GET['fecha_ini'];
$fecha_fin = $_GET['fecha_fin'];
$fecha_ini_horas = DateTime::createFromFormat('m/d/Y', fecha_ini);
$fecha_fin_horas = DateTime::createFromFormat('m/d/Y', fecha_fin);
    
answered by 27.03.2018 / 19:56
source