Exploring and Thinking

Node.js 取得上個月的日期字串

取年份要使用 getFullYear()才會有完整正確的數字。

如果要取當月,因為月份的算法是0~11,需改為(MyDate.getMonth()+1)。
1
2
3
4
5
6
var MyDate = new Date();
var MyDateString;

MyDateString = MyDate.getFullYear() + '/' + ('0' + MyDate.getMonth()).slice(-2);

console.log(MyDateString);

結果:

Ians-MBP:Desktop ian$ node LastMonth.js
2014/07

取前一天:

1
2
3
4
5
6
var MyDate = new Date();
var MyDateString;

MyDate.setDate(MyDate.getDate() - 1); // 取前一日,自行依備份日期調整

MyDateString = MyDate.getFullYear() + '/' + ('0' + (MyDate.getMonth()+1)).slice(-2) + '/' + ('0' + MyDate.getDate()).slice(-2);  //日期補零 2014/08/16

原有取得的日期沒有補0,因此才有加0和slice(-2)的轉換,原理如下。(原文網址:http://stackoverflow.com/questions/3605214/javascript-add-leading-zeroes-to-date)

To explain, .slice(-2) gives us the last two characters of the string.
So no matter what, we can add "0" to the day or month, and just ask for the last two since those are always the two we want.
So if the MyDate.getMonth() returns 9, it will be:
("0" + "9") // Giving us "09"
so adding .slice(-2) on that gives us the last two characters which is:
("0" + "9").slice(-2)
"09"
But if MyDate.getMonth() returns 10, it will be:
("0" + "10") // Giving us "010"
so adding .slice(-2) gives us the last two characters, or:
("0" + "10").slice(-2)
"10"
Share:

熱門文章

標籤