2011-12-05 12 views

Respuesta

30
<script> 
Date.prototype.getWeek = function(start) 
{ 
     //Calcing the starting point 
    start = start || 0; 
    var today = new Date(this.setHours(0, 0, 0, 0)); 
    var day = today.getDay() - start; 
    var date = today.getDate() - day; 

     // Grabbing Start/End Dates 
    var StartDate = new Date(today.setDate(date)); 
    var EndDate = new Date(today.setDate(date + 6)); 
    return [StartDate, EndDate]; 
} 

// test code 
var Dates = new Date().getWeek(); 
alert(Dates[0].toLocaleDateString() + ' to '+ Dates[1].toLocaleDateString()) 
</script> 

Creo que esto funciona.

+0

u mucho funciona !!!!!!!! – Vishnu

+1

@ user725184, Har du encontró satisfactoria la respuesta, por favor acepte la respuesta. Ver http://meta.stackexchange.com/questions/5234/how-does-accepting-an-answer-work por más. –

+0

Un poco desagradable, ya que la falta que cambia la hora y fecha del objeto Date. – RobG

0

Puede modificar el valor de retorno para satisfacer sus necesidades, en este momento simplemente devuelve el objeto completo del domingo.

Date.prototype.endWeek=function(){ 
    return new Date(this.getFullYear(), this.getMonth(),(7-this.getDay())+this.getDate()); 
} 

//call like this 
var myDate = new Date(); 
var Sunday = myDate.endWeek(); 
alert("Sunday falls on "+ Sunday.getDate()); 
11

La siguiente función hará el truco:

// return an array of date objects for start (monday) 
// and end (sunday) of week based on supplied 
// date object or current date 
function startAndEndOfWeek(date) { 

    // If no date object supplied, use current date 
    // Copy date so don't modify supplied date 
    var now = date? new Date(date) : new Date(); 

    // set time to some convenient value 
    now.setHours(0,0,0,0); 

    // Get the previous Monday 
    var monday = new Date(now); 
    monday.setDate(monday.getDate() - monday.getDay() + 1); 

    // Get next Sunday 
    var sunday = new Date(now); 
    sunday.setDate(sunday.getDate() - sunday.getDay() + 7); 

    // Return array of date objects 
    return [monday, sunday]; 
} 

// Mon Nov 12 2012 00:00:00 
// Sun Nov 18 2012 00:00:00 
alert(startAndEndOfWeek(new Date(2012,10,14)).join('\n')); 
5

Prueba esto:

var current = new Date();  // get current date  
var weekstart = current.getDate() - current.getDay() +1;  
var weekend = weekstart + 6;  // end day is the first day + 6 
var monday = new Date(current.setDate(weekstart)); 
var sunday = new Date(current.setDate(weekend)); 
+0

THX para esto, buena copiar y pegar y de trabajo de pura JS – zyrex

+0

mejor respuesta para mí. – saawsann

+0

meses Esta semana shouldnt workwith superpuestas. – Habib

3

SetDate voluntad establece el día del mes. Usando setDate durante el inicio y el final del mes, dará lugar a la semana equivocada

var curr = new Date("08-Jul-2014"); // get current date 
var first = curr.getDate() - curr.getDay(); // First day is the day of the month - the day of the week 
var last = first + 6; // last day is the first day + 6 
var firstday = new Date(curr.setDate(first)); // 06-Jul-2014 
var lastday = new Date(curr.setDate(last)); // 12-Jul-2014 

Si el ajuste es Fecha 01-Jul-2014, se mostrará como firstday 29-Jun-2014 y Lastday como 05-Jun- 2014 en lugar de 05-jul-2014. Así que para solucionar este problema usé

var curr = new Date(); 
day = curr.getDay(); 
firstday = new Date(curr.getTime() - 60*60*24* day*1000); // will return firstday (i.e. Sunday) of the week 
lastday = new Date(curr.getTime() + 60 * 60 *24 * 6 * 1000); // adding (60*60*6*24*1000) means adding six days to the firstday which results in lastday (Saturday) of the week 
+0

La única solución aquí que maneja todos los casos especiales, gracias – Thomas

1

En los otros ejemplos, tendrá un problema cuando el domingo caiga en otro mes. Esto debería resolver el problema:

var today, todayNumber, mondayNumber, sundayNumber, monday, sunday; 
    today = new Date(); 
    todayNumber = today.getDay(); 
    mondayNumber = 1 - todayNumber; 
    sundayNumber = 7 - todayNumber; 
    monday = new Date(today.getFullYear(), today.getMonth(), today.getDate()+mondayNumber); 
    sunday = new Date(today.getFullYear(), today.getMonth(), today.getDate()+sundayNumber); 
0

espero que esto va a funcionar para usted:

Date.prototype.getWeekEndDate = function() { 
    diff = 6 - this.getDay(); 
    if (diff < 0) { 
     diff += 6; 
    } 
    this.setDate(this.getDate() + (1 * diff)); 
    return this; 
} 
Date.prototype.getWeekStartDate = function() { 
    diff = this.getDay() - 6; 
    if (diff < 0) { 
     diff += 7; 
    } 
    return this.setDate(this.getDate() + (-1 * diff)); 
} 

Estos método devolverá fecha de inicio y final de la semana.

0
  1. Problemas de meses diferentes también se corrige con el código siguiente.
  2. Se agregó la función de formato "M.dd.aaaa".

    función startAndEndOfWeek (setDate) { era día = null; era la fecha = null; el mes = null; el año = null; era mon = null; era mar = null; se casó = null; era jue. = null; estaba libre = null; se añadió = null; era sol = null;

    var now = setDate ? new Date(setDate) : new Date(); 
    now.setHours(0,0,0,0); 
    
    var monday = new Date(now); var tuesday = new Date(now); var wednesday = new Date(now); var thursday = new Date(now); 
    var friday = new Date(now); var saturday = new Date(now); var sunday = new Date(now); 
    
    if(new Date(now).getDay() == 0) 
    { 
        monday.setDate(monday.getDate() - 6); 
        tuesday.setDate(tuesday.getDate() - 5); 
        wednesday.setDate(wednesday.getDate() - 4); 
        thursday.setDate(thursday.getDate() - 3); 
        friday.setDate(friday.getDate() - 2); 
        saturday.setDate(saturday.getDate() - 1); 
        sunday.setDate(sunday.getDate() - 0); 
    } 
    else 
    { 
        monday.setDate(monday.getDate() - monday.getDay() + 1); 
        tuesday.setDate(tuesday.getDate() - tuesday.getDay() + 2); 
        wednesday.setDate(wednesday.getDate() - wednesday.getDay() + 3); 
        thursday.setDate(thursday.getDate() - thursday.getDay() + 4); 
        friday.setDate(friday.getDate() - friday.getDay() + 5); 
        saturday.setDate(saturday.getDate() - saturday.getDay() + 6); 
        sunday.setDate(sunday.getDate() - sunday.getDay() + 7); 
    } 
    
    date = monday.getDate(); 
    month = monday.getMonth(); 
    year = monday.getFullYear(); 
    mon = getMonthValue(month) + "." + getDateValue(date) + "." + year; 
    
    date = tuesday.getDate(); 
    month = tuesday.getMonth(); 
    year = tuesday.getFullYear(); 
    tue = getMonthValue(month) + "." + getDateValue(date) + "." + year; 
    
    date = wednesday.getDate(); 
    month = wednesday.getMonth(); 
    year = wednesday.getFullYear(); 
    wed = getMonthValue(month) + "." + getDateValue(date) + "." + year; 
    
    date = thursday.getDate(); 
    month = thursday.getMonth(); 
    year = thursday.getFullYear(); 
    thu = getMonthValue(month) + "." + getDateValue(date) + "." + year; 
    
    date = friday.getDate(); 
    month = friday.getMonth(); 
    year = friday.getFullYear(); 
    fri = getMonthValue(month) + "." + getDateValue(date) + "." + year; 
    
    date = saturday.getDate(); 
    month = saturday.getMonth(); 
    year = saturday.getFullYear(); 
    sat = getMonthValue(month) + "." + getDateValue(date) + "." + year; 
    
    date = sunday.getDate(); 
    month = sunday.getMonth(); 
    year = sunday.getFullYear(); 
    sun = getMonthValue(month) + "." + getDateValue(date) + "." + year; 
    
    return [mon, tue , wed, thu, fri, sat, sun]; 
    

    }

    función getMonthValue (mes) { interruptor (meses) {case 0: return "Jan"; romper; caso 1: retorno "Febrero"; romper; el caso 2: el regreso "Marcha"; romper; caso 3: el retorno "Abril"; romper; caso 4: return "mayo"; romper; caso 5: retorno "Junio"; romper; caso 6: return "Navidad"; romper; caso 7: retorno "Agosto"; romper; caso 8: return "sep"; romper; caso 9: return "octubre"; romper; caso 10: return "noviembre"; romper; caso 11: return "Dec"; romper; }} función getDateValue (días) {if (parseInt (días) < 10) {return "0" + días; } día regresar; }

1

Sobre la base de la respuesta de RobG, que terminó con esta dos conseguir dos semana a partir de la medianoche del lunes y finalizará el domingo 23: 59: 59,999.

var weekMap = [6, 0, 1, 2, 3, 4, 5]; 

    function startAndEndOfWeek(date) { 
    var now = new Date(date); 
    now.setHours(0, 0, 0, 0); 
    var monday = new Date(now); 
    monday.setDate(monday.getDate() - weekMap[monday.getDay()]); 
    var sunday = new Date(now); 
    sunday.setDate(sunday.getDate() - weekMap[sunday.getDay()] + 6); 
    sunday.setHours(23, 59, 59, 999); 
    return [monday, sunday]; 
    } 
+1

este es perfecto para todos los escenarios –

+0

Lo estamos usando en las funciones de lista CouchDB para agregar sumas por semana para documentos con marcas de tiempo, y parece funcionar bastante bien hasta ahora . – jo2

0

ligeramente modificada respuesta de @ReadWriteCode, este også funciona con éxito con diferentes meses.

Date.prototype.getWeek = function() 
{ 
    var today = new Date(); 
    var day = today.getDay(); 
    var date = today.getDate() - day; 

     // Grabbing Start/End Dates 
    var StartDate = new Date(); 
    var EndDate = new Date(); 
    StartDate.setHours(0,0,0,0); EndDate.setHours(0,0,0,0); 
    StartDate.setDate(today.getDate()-day); 
    EndDate.setDate(today.getDate()-day+6); 
    return { 
     startDate:StartDate, 
     endDate: EndDate 
    }; 
} 
var thisWeekDates=new Date().getWeek(); 
Cuestiones relacionadas