Convert from String to Date jquery dd-mm-yyyy

1

I need to convert a date that comes as a string to date, it is already formatted from mysql to '% d-% m-% Y', but it is in the view with jquery and recognizes it as a string.

I receive data converted to '% d-% m-% Y' in php codeigneiter:

$this->db->select("DATE_FORMAT(auto.fecha_reserva, '%d-%m-%Y') as fecha", FALSE);
$this->db->from('auto');
$datos=$this->db->get();
return $datos->result();

I get the data:

$.each(obj.resultado, function (ind, elem) { 
ejemplo : alert(typeof("30-10-2017")); //viene desde la query
 alert(typeof(elem.fecha));//retorna un String "dd-mm-yyyy
 //necesito que elem.fecha sea un date en dd-mm-yyyy 
 //lo ideal seria formatearla sin uso de plugins

});
    
asked by Javier Antonio Aguayo Aguilar 26.09.2017 в 16:13
source

3 answers

-1

Date ()

Using new Date(número) , create a new date object such as zero time plus the number.

The zero hour is 01 January 1970 00:00:00 UTC.

The number is specified in milliseconds.

var dateVar = "2010-10-30";
console.log("String: "+dateVar);
var d=new Date(dateVar);
console.log("Date: "+d);

I'll add some code. So you can see how the theme of conversions works. In front of each data comes the type.

var dateVar = "2010-10-30";
console.log(jQuery.type(dateVar)+": "+dateVar);

var d = new Date(dateVar);
console.log(jQuery.type(d)+": "+d);

var n = d.toLocaleDateString();
console.log(jQuery.type(n)+": "+n);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    
answered by 26.09.2017 в 16:34
-1

You might consider creating a method that receives the string as a parameter and returns an object Date .

For example, for date formatted: 30-10-2017

function toDate(cadenaFecha){

  var patron = /^(\d{1,2})-(\d{1,2})-(\d{4})$/;
  var arrayFecha = cadenaFecha.match(patron);
  var fecha = new Date(arrayFecha[3], arrayFecha[2] - 1, arrayFecha[1]);

  return fecha;
  
}

console.log(toDate("30-10-2017"));
    
answered by 26.09.2017 в 17:19
-1

From the string you have in elem.fecha , you need to extract the day, month and year values separately. For your example 30-10-2017 you can get them by calling the function split("-") , which will return an arrangement with each element of the date:

var arregloFecha = elem.fecha.split("-");

To build the object of type Date you can use the constructor new Date(anio, mes, dia) . The month field can have a value between 0 and 11, where 0 represents January and 11 December. Therefore, it is necessary to subtract 1 from the month value obtained in arregloFecha before using it in the constructor.

Your complete code would look like this:

var arregloFecha = elem.fecha.split("-");
var anio = arregloFecha[2];
var mes = arregloFecha[1] - 1;
var dia = arregloFecha[0];

var fecha = new Date(anio, mes, dia); // fecha será de tipo Date

More information about Date in this link

    
answered by 27.09.2017 в 07:21