Convert dd-mm-YYYY HH :: mm: ss to date in javascript [duplicate]

0

How can I convert a date in string dd-mm-YYYY HH :: mm: ss to the javascript date and inversely the conversion of the javascript date to a string date.

So far I have this working:

fech = $("#fechaHoraInicioAgenda").val().split("-");
var fecha = new Date(fech[2], fech[1] - 1, fech[0]);

I do not know how much it is possible to carry out the conversion taking the date and time format.

    
asked by Santiago Muñoz 27.04.2017 в 21:28
source

1 answer

5

With pure Javascript you could do the following to convert the date to Date and convert it back to the same format as a string.

var initialDate = "24-04-2016 04:24:00"

//Dividimos la fecha primero utilizando el espacio para obtener solo la fecha y el tiempo por separado
var splitDate= initialDate.split(" ");
var date=splitDate[0].split("-");
var time=splitDate[1].split(":");

// Obtenemos los campos individuales para todas las partes de la fecha
var dd=date[0];
var mm=date[1]-1;
var yyyy =date[2];
var hh=time[0];
var min=time[1];
var ss=time[2];

// Creamos la fecha con Javascript
var fecha = new Date(yyyy,mm,dd,hh,min,ss);

// De esta manera se puede volver a convertir a un string
var formattedDate = ("0" + fecha.getDate()).slice(-2) + '-' + ("0" + (fecha.getMonth() + 1)).slice(-2) + '-' + fecha.getFullYear() + ' ' + ("0" + fecha.getHours()).slice(-2) + ':' + ("0" + fecha.getMinutes()).slice(-2) + ':' + ("0" + fecha.getSeconds()).slice(-2);

But I think it would be advisable to check the library moment.js ( link ) because it makes it easy to work with dates and their formats in Javascript.

    
answered by 27.04.2017 / 22:02
source