2010-08-26 8 views
18

Realmente agradecería algo de ayuda al crear JavaScript que eventualmente se utilizará en Selenium que establece automáticamente una fecha con 10 días de anticipación a partir de la fecha actual y se muestra en el siguiente formato dd/mm/aaaa.Establecer la fecha 10 días en el futuro y formatear a dd/mm/aaaa (ej. 21/08/2010)

Actualmente tengo el guión abajo, pero ahora no recibo ninguna parte con él:

var myDate=new Date(); 
myDate.now.format(myDate.setDate(myDate.getDate()+5),("dd/mm/yyyy"); 

Cualquier ayuda sería muy apreciada.

+0

¿Cuál es el error o problema que enfrenta? –

+3

Tengo que señalar un poco de friki-ironía aquí. Una pregunta de fecha JavsScript publicada por "Julian": todas las fechas en JavaScript se basan en el sistema Julian Date http://en.wikipedia.org/wiki/Julian_day#Julian_Date – Fenton

Respuesta

19

Aquí es un ejemplo de conseguir la fecha futura ...

var targetDate = new Date(); 
targetDate.setDate(targetDate.getDate() + 10); 

// So you can see the date we have created 
alert(targetDate); 

var dd = targetDate.getDate(); 
var mm = targetDate.getMonth() + 1; // 0 is January, so we must add 1 
var yyyy = targetDate.getFullYear(); 

var dateString = dd + "/" + mm + "/" + yyyy; 

// So you can see the output 
alert(dateString); 

Hay algunas formas más elegantes para dar formato a las fechas, los ejemplos se pueden encontrar en los siguientes destinos:

http://www.west-wind.com/Weblog/posts/282495.aspx

http://www.svendtofte.com/javascript/javascript-date-string-formatting/

+0

¿Por qué no es posible usar 'format' o' toString 'después de usar setDate? –

0

Necesitaba hacer algo como esto, pero necesitaba el resultado en línea. Así que esto es lo que funcionó para mí para obtener la fecha de 10 días a partir de ahora:

new Date((new Date()).getTime() + (10 * 86400000)) 
+0

Esto devuelve la fecha incorrecta si usa ciertas fechas. – MasterP

-1

Lo que quiero hacer, es crear una costumbre DateHelper objeto que se parece a esto:

var DateHelper = { 
 
    addDays : function(aDate, numberOfDays) { 
 
     aDate.setDate(aDate.getDate() + numberOfDays); // Add numberOfDays 
 
     return aDate;         // Return the date 
 
    }, 
 
    format : function format(date) { 
 
     return [ 
 
      ("0" + date.getDate()).slice(-2),   // Get day and pad it with zeroes 
 
      ("0" + (date.getMonth()+1)).slice(-2),  // Get month and pad it with zeroes 
 
      date.getFullYear()       // Get full year 
 
     ].join('/');         // Glue the pieces together 
 
    } 
 
} 
 

 
// With this helper, you can now just use one line of readable code to : 
 
// --------------------------------------------------------------------- 
 
// 1. Get the current date 
 
// 2. Add 10 days 
 
// 3. Format it 
 
// 4. Output it 
 
// --------------------------------------------------------------------- 
 
document.body.innerHTML = DateHelper.format(DateHelper.addDays(new Date(), 10));

(véase también this Fiddle)

6

Probar:

new Date(Date.now() + (1000 /*sec*/ * 60 /*min*/ * 60 /*hour*/ * 24 /*day*/ * 10)) 
0

Este tema de la página original es de 2010. Por lo tanto, añade esta respuesta en agosto de 2017. Es una solución simple que funciona bien para la creación de un fecha de rodadura gama basado en la fecha actual.

Por ejemplo: si hoy es 28 de agosto de 2017 y desea una fecha de inicio de -7 días en el pasado y una fecha futura de 23 días en el futuro, el siguiente código JavaScript generará una cadena de rango de fecha de : 21 agosto-20 septiembre 2017

Luego, al día siguiente, el 29 de agosto de 2017, el intervalo de fechas leerán 22 agosto-21 septiembre 2017

Nota: si es necesario, puede modificar el código para establecer la fecha de inicio o futura estática.

Para utilizarlo en el código HTML:

El evento se realiza: <script>document.write(dateRange)</script>

se Rendimiento:

El evento se lleva a cabo: 21 agosto hasta 20 septiembre, 2017

var month = new Array(); 
month[0] = "January"; 
month[1] = "February"; 
month[2] = "March"; 
month[3] = "April"; 
month[4] = "May"; 
month[5] = "June"; 
month[6] = "July"; 
month[7] = "August"; 
month[8] = "September"; 
month[9] = "October"; 
month[10] = "November"; 
month[11] = "December"; 

var startDate = new Date(); 
startDate.setDate(startDate.getDate() -7); 

var futureDate = new Date(); 
futureDate.setDate(futureDate.getDate() + 23); 

var m1 = month[startDate.getMonth()]; 
var d1 = startDate.getDate(); 
var y1 = startDate.getFullYear(); 

var m2 = month[futureDate.getMonth()]; 
var d2 = futureDate.getDate(); 
var y2 = futureDate.getFullYear(); 

var dateRange = m1 + ' ' + d1 + ' thru ' + m2 + ' ' + d2 + ', ' + y2; 

// alert(dateRange); use alert function to test the date range 
Cuestiones relacionadas