JQuery: pass variable string to date object

I have a page with a series of variables that contain a date in string format (yyyy-mm-dd) , which comes from using the .js moment.

Is there a way to pass such a variable to a Javascript or date object. convert it to a javascript date object? I'm not interested in the time until I can get a date converted to a date object that would be great.

I tried the following, but this does not work, and I could not find a way using moment.js:

var newVar = new Date(dateVar); 

Thanks so much for any help with this, Tim.

+8
javascript jquery datetime momentjs date-arithmetic
source share
3 answers

First of all I will say that the following should work for you.

 var dateVar = "2010-10-30"; var d=new Date(dateVar); 

if you speak above does not work, check below one -

 var dateVar = "2010-10-30"; var dsplit = dateVar.split("-"); var d=new Date(dsplit[0],dsplit[1]-1,dsplit[2]); 

to test jsfiddle check .. both work fine .. jsfiddle

+21
source share

console.log() used to show the result, run this and you will understand the code

  <script type='text/javascript'> var StringDate = "2013-4-13" var date = StringDate.split("-"); console.log(date[0]); console.log(date[1]); console.log(date[2]); NewDate = new Date(date[0],date[1]-1,date[2]);//Date object console.log(NewDate); </script> 
+5
source share

To solve this problem, I created a function that controls the text change for today:

My examples work with a date like this: Jun / 1/2016 to 2016-06-01 you can rebuild the function so that your format works ...

The zura to the left of the numbers is added according to the date type format.

 function textoafecha(texto) { hasNumber = /\d/; // Contiene el pedazo del texto que contiene el mes mestexto = texto.substr(0,3); // Contiene el pedazo de texto que contiene el primer numero del dia diatextonumero1 = texto.substr(4,1); diatextonumero2 = texto.substr(5,1); // Si el texo contiene un numero... if (hasNumber.test(diatextonumero2)) { dia = texto.substr(4,2); anotexto = texto.substr(7,4); } else { dia = texto.substr(4,1); dia = "0"+ dia; anotexto = texto.substr(6,4); } switch (mestexto) { case "Jan" : mesnumero = "01"; break; case "Feb" : mesnumero = "02"; break; case "Mar" : mesnumero = "03"; break; case "Apr" : mesnumero = "04"; break; case "May" : mesnumero = "05"; break; case "Jun" : mesnumero = "06"; break; case "Jul" : mesnumero = "07"; break; case "Aug" : mesnumero = "08"; break; case "Sep" : mesnumero = "09"; break; case "Oct" : mesnumero = "10"; break; case "Nov" : mesnumero = "11"; break; case "Dic" : mesnumero = "12"; break; default : break; } fechaformateada = anotexto + "-" + mesnumero + "-" + dia; return fechaformateada; } 
+1
source share

All Articles