2009-03-03 47 views
19

Vui lòng bất kỳ ai chia sẻ mã này để tìm ngày đầu tiên của tháng trước đó từ ngày hiện tại bằng JavaScript. Ví dụ: nếu ngày hiện tại là ngày 25 tháng 1 năm 2009, tôi sẽ nhận được kết quả vào ngày 1 tháng 12 năm 2008.Nhận ngày đầu tiên của tháng trước đó từ ngày hiện tại trong JavaScript

+0

có thể lặp lại [Tìm ngày đầu tiên của tháng trước trong javascript] (http://stackoverflow.com/questions/605113/ find-first-day-of-before-month-in-javascript) –

+0

Kiểm tra điều này: http://stackoverflow.com/questions/605113/find-first-day-of-previous-month-in-javascript – Learning

Trả lời

3

Kiểm tra liên kết này:

http://blog.dansnetwork.com/2008/09/18/javascript-date-object-adding-and-subtracting-months/

EDIT: Tôi đã gõ gõ lên một ví dụ:

Date.prototype.SubtractMonth = function(numberOfMonths) { 
var d = this; 
d.setMonth(d.getMonth() - numberOfMonths); 
d.setDate(1); 
return d; 
} 

$(document).ready(function() { 
    var d = new Date(); 
    alert(d.SubtractMonth(1)); 
}); 

Andrew

+0

Xin chào Andrew , giải pháp bạn đã nói trả lại chính xác 30 ngày kể từ ngày hiện tại. Tôi cần ngày đầu tiên của tháng trước bất kể ngày nào trong tháng hiện tại. –

+0

cảm ơn dude !!!! Tôi đã nhận được liên kết –

+0

bị lỗi: ( –

49

đủ thẳng thắn, với date methods:

var x = new Date(); 
    x.setDate(1); 
    x.setMonth(x.getMonth()-1); 
+0

trừ khi nó bị lỡ khi năm thay đổi? – Learning

+1

Không có nó sẽ tự động điều chỉnh ngày –

+1

Đây là lý do tại sao bạn làm điều này với các phương pháp ngày gốc hơn là rối tung xung quanh với lịch của bạn arithmatic. yêu JS :) – annakata

2

Thỏa thuận với năm cập nhật khi di chuyển từ tháng một-tháng mười hai

var prevMonth = function(dateObj) { 
 
\t var tempDateObj = new Date(dateObj); 
 

 
\t if(tempDateObj.getMonth) { 
 
\t \t tempDateObj.setMonth(tempDateObj.getMonth() - 1); 
 
\t } else { 
 
\t \t tempDateObj.setYear(tempDateObj.getYear() - 1); 
 
\t \t tempDateObj.setMonth(12); 
 
\t } 
 

 
\t return tempDateObj 
 
}; 
 

 
var wrapper = document.getElementById('wrapper'); 
 

 
for(var i = 0; i < 12; i++) { 
 
\t var x = new Date(); 
 
    var prevDate = prevMonth(x.setMonth(i)); 
 
\t var div = document.createElement('div'); 
 
    div.textContent = 
 
    "start month/year: " + i + "/" + x.getFullYear() + 
 
    " --- prev month/year: " + prevDate.getMonth() + 
 
    "/" + prevDate.getFullYear() + 
 
    " --- locale prev date: " + prevDate.toLocaleDateString(); 
 
    wrapper.appendChild(div); 
 
}
<div id='wrapper'> 
 
</div>

Các vấn đề liên quan