[英]Current Week [Javascript]
I use this function to get the current week 我使用此功能获取当前星期
Date.prototype.getWeek = function(start)
{
start = start || 1;
today = new Date(this.setHours(0, 0, 0, 0));
var day = today.getDay() - start;
date = today.getDate() - day;
var giorni = [];
var currdate;
for(var i = 0;i<7;i++){
if(getNumberOfDays(today.getFullYear(),today.getMonth()) == currdate){
var changed=1;
var newdate=new Date(today.getFullYear(),today.getMonth()+1,1);
giorni.push(newdate);
}else{
if(changed==1){
var dt = newdate.getDate();
giorni.push(new Date(today.getFullYear(),today.getMonth()+1,dt+1));
newdate = new Date(today.getFullYear(),today.getMonth(),dt+1);
}else{
giorni.push(new Date(today.setDate(date+i)));
}
}
currdate = date+i;
}
}
var Dates = new Date().getWeek();
But in this week it displays wrong dates..(From 30 November to 6 November) 但是在这个星期它显示了错误的日期。(从11月30日到11月6日)
Any suggestion? 有什么建议吗? ( this is the plunker -> plnkr.co/edit/48NyxngWNGIlOps1Arew?p=preview)
(这是the人-> plnkr.co/edit/48NyxngWNGIlOps1Arew?p=preview)
Here is an answer for getting start of the week and other things using momentjs. 这是使用momentjs开始新的一周的答案。
function getWeekFor(dateTime) {
var days = [];
var sunday = moment(dateTime).startOf('week');
for (var i = 1; i < 8; i++) {
days.push(moment(sunday).add(i, 'days'));
}
return days; // returns a list of moment objects
}
function shiftWeek(add, dateTime) {
// this will just increment or decrement the week
var sunday = moment(dateTime).startOf('week');
sunday.add(1, 'd');
if (add) {
sunday.add(1, 'w');
} else {
sunday.subtract(1, 'w');
}
return sunday; // returns a moment object
}
function getWeekDate(dateTime) {
var sunday = moment(dateTime).startOf('week');
var monday = sunday.add({day: 1}).clone();
return 'Week Commencing ' + monday.format('Do'); // a nicely formatted string of the week commencing
}
function getStartOfWeek(dateTime) {
var sunday = moment(dateTime).startOf('week');
var monday = sunday.add({day: 1}).clone();
return monday; // the monday that started the week as a moment object
}
It is pretty straightforward and self explanatory. 这是非常简单和自我解释的。 It uses the methods
startOf
and add
passing in w
as the unit to add. 它使用方法
startOf
和add
传入w
作为要添加的单位。 w == week
. w == week
。
And if you don't want a moment object, heres a list of other objects you can get from it: 如果您不希望使用瞬间对象,则可以从中获得以下其他对象的列表:
moment().toDate(); // returns javascript Date
moment().toArray(); // This returns an array that mirrors the parameters from new Date()
moment().toJSON(); // it will be represented as an ISO8601 string, adjusted to UTC.
This is because you are changing date manually 这是因为您正在手动更改日期
giorni.push(new Date(today.getFullYear(),today.getMonth()+1,dt+1));
Instead of this try 代替这个尝试
var today = new Date()
today.setDate(today.getDate()+1);
giorni.push(new Date(today.getTime()));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.