Date Number increases wrong in JavaScript - javascript

I have a problem with creating a calendar in JavaScript. I want to display dates from Monday to Sunday. So this is my DateSet function:
dateSets(year) {
const today = new Date();
year = today.getFullYear();
let firstDayOfWeek = this.getDateOfWeek(this.currentWeekNumber, year);
let dates = [];
for (let i = 0; i < 7; i++) {
dates.push(
new Date(firstDayOfWeek.setDate(firstDayOfWeek.getDate() + i))
);
}
return dates;
}
getDateOfWeek(this.currentWeekNumber, year) gets the Monday of the week. But with this code displays 9/8/2021 10/8/2021 12/8/2021 15/8/2021 19/8/2021 24/8/2021 30/8/2021.
So when I change the i in the for with 1 it displays like this but I cannot use this because I cannot get Monday: 10/8/2021 11/8/2021 12/8/2021 13/8/2021 14/8/2021 15/8/2021 16/8/2021.

Related

How to manipulate date using Javascript

How can I achieve this sequence of date output if the user input is 04-29-2022 and the output is like this
What I want:
2022-05-14
2022-05-29
2022-06-14
2022-06-29
2022-07-14
2022-07-29
2022-08-14
2022-08-29
my code output
2022-05-13
2022-05-28
2022-06-12
2022-06-27
2022-07-12
2022-07-27
2022-08-11
2022-08-26
var dateRelease = new Date("04-29-2022")
const terms = 8
for (let i = 0; i < terms; i++) {
console.log(new Date(dateRelease.setDate(dateRelease.getDate() + 15)).toISOString().slice(0, 10))
}
Here is a function that takes the day of the month in the given date and determines which other date of the month would be needed in the output (either 15 more or 15 less). Then it generates dates alternating between those two date-of-the-month, and when it is the lesser of those two, incrementing the month. In case a date is invalid and automatically overflows into the next month, it is corrected to the last day of the intended month.
To format the date in the output, it is better to not use toISODateString as that interprets the date as a UTC Date, while new Date("2022-04-29") interprets the given string as a date in the local time zone. This can lead to surprises in some time zones. So I would suggest using toLocaleDateString with a locale that produces your desired format.
Here is the code:
function createSchedule(date, count) {
date = new Date(date);
let day = date.getDate();
let k = +(day > 15);
let days = k ? [day - 15, day] : [day, day + 15];
let result = [];
for (let i = 0; i < count; i++) {
k = 1 - k;
date.setDate(days[k]);
// When date overflows into next month, take last day of month
if (date.getDate() !== days[k]) date.setDate(0);
if (!k) date.setMonth(date.getMonth() + 1);
result.push(date.toLocaleDateString("en-SE"));
}
return result;
}
var dateRelease = new Date("2022-04-29");
var result = createSchedule(dateRelease, 25);
console.log(result);
var dateRelease = new Date("04-29-2022")
const terms = 8
for (let i = 0; i < terms; i++) {
let date = new Date(dateRelease.setDate(dateRelease.getDate() + 15)).toLocaleDateString('en-US');
let format = date.split('/').map(d => d.padStart(2 ,'0')).join('-')
console.log(format);
}

show 2 week in the past ( vue.js)

Hi i have this script ( vue.js ) i can see the next 2 weeks works good i must change that i can see 2 weeks on the past ..
Thanks
methods: {
// Get all days without sunday:
dates(index) {
var week = new Array();
let current = new Date();
// Starting Monday not Sunday
current.setDate((current.getDate() - current.getDay() +1));
for (var i = 0; i < 13; i++) {
let date = new Date(current);
week.push(moment(date).format('DD.MM.YY'));
current.setDate(current.getDate() +1);
}
return week[index];
},
If you want to go back in time, you need to subtract from the current date:
methods: {
// Get all days without sunday:
dates(index) {
var week = new Array();
let current = new Date();
// Starting Monday not Sunday
current.setDate((current.getDate() - current.getDay() +1));
for (var i = 0; i < 13; i++) {
let date = new Date(current);
week.push(moment(date).format('DD.MM.YY'));
current.setDate(current.getDate() - 1); // <-- this line changed
}
return week[index];
},
Try this:
function dates(index) {
var week = new Array();
let current = moment().subtract(1, 'days');
for (var i = 0; i < 12; i++) {
week.push(current.format('DD.MM.YY'));
current = current.subtract(1, 'days')
}
console.log(week);
return week[index];
}
console.log(dates(2));
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.27.0/moment.min.js"></script>

MomentJS getting previous dates relative to today

Is there anyway to get the days past the current day using MomentJS?
For example suppose it is January 5, 2018, how would I get the previous dates from January 1, 2018 through to January 5, 2018 ?
My current code looks like this:
const monthArr = [];
const dayArr= [];
const currentDate = moment(new Date()).format("DD");
for (let i = 0; i < +currentDate; i++) {
const month = moment(new Date())
.subtract(i, "day")
.format("MMYYYY");
const day = moment(new Date())
.subtract(i, "day")
.format("MMDDYYYY");
console.log("month" + month);
console.log("day" + day);
let monthObj = {};
let dailyObj = {};
monthArr.push(
(monthObj = {
data: {
[month]: Object.assign({}, document)
}
})
);
day.push(
(dailyObj = {
data: {
[day]: Object.assign({}, document)
}
})
);
monthly(user_id, monthArr[i]) &&
daily(user_id, dayArr[i]);
}
The code in the OP seems very inefficient and far more complex than required.
To generate a series of formatted strings for dates from today to the start of the month only needs one Date and some very simple arithmetic and formatting. It really doesn't need a library nor any date arithmetic, e.g.
// Pad single digit number with leading zero
function pad(n){
return (n < 10? '0' : '') + n;
}
var today = new Date(),
year = today.getFullYear(),
month = pad(today.getMonth() + 1),
day,
i = today.getDate();
do {
day = pad(i);
console.log(`Month: ${month + year}`);
console.log(`Day: ${month + day + year}`);
} while (--i)
There are a number of other issues with your code, but they're not directly related to the question.

Get all days of the week given a day

I'm trying to make a function to get all the days of the week given the current day. I had a function that i thought was working until i noticed that if the day of the week is near the end of the month, like for example February, i get weird data. Anyone know whats going on and how to fix it?
function days(current) {
var week = new Array();
// Starting Monday not Sunday
var first = ((current.getDate() - current.getDay()) + 1);
for (var i = 0; i < 7; i++) {
week.push(
new Date(current.setDate(first++))
);
}
return week;
}
var input = new Date(2017, 1, 27);
console.log('input: %s', input);
var result = days(input);
console.log(result.map(d => d.toString()));
.as-console-wrapper{min-height:100%}
If you don't want to use some kind of other library like Moment.js you can also change your function a little and then it will work. Try this:
function dates(current) {
var week= new Array();
// Starting Monday not Sunday
current.setDate((current.getDate() - current.getDay() +1));
for (var i = 0; i < 7; i++) {
week.push(
new Date(current)
);
current.setDate(current.getDate() +1);
}
return week;
}
console.log(dates(new Date(2017, 1, 27)));
You can use Moment.js library - utility library for dates/time operations
Here's examplary code to get current week's dates starting from monday:
function getThisWeekDates() {
var weekDates= [];
for (var i = 1; i <= 7; i++) {
weekDates.push(moment().day(i));
}
return weekDates;
}
var thisWeekDates = getThisWeekDates();
thisWeekDates.forEach(function(date){ console.log(date.format());});
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.22.2/moment.js"></script>
The code above prints following results to the console:
2017-03-20T21:26:27+01:00
2017-03-21T21:26:27+01:00
2017-03-22T21:26:27+01:00
2017-03-23T21:26:27+01:00
2017-03-24T21:26:27+01:00
2017-03-25T21:26:27+01:00
2017-03-26T21:26:27+02:00
I will trace your code using your example of Feb 27, 2017:
first = 27 - 1 + 1 = 27
loop:
Feb.setDate(27) = 27 feb
Feb.setDate(28) = 28 feb
Feb.setDate(29) = Not 29 days in Feb. So it sets current to 29-28 = 1st day of March
March.setDate(30) = March 30
March.setDate(31) = March 31
March.setDate(32) = Not 32 days in March. So it sets current to 31-32 = 1st of April..
April.setDate(33) = Not 33 days in April. So it sets current day 33-30 = 3rd day of May.
Please note that I used the shorthand of Month.setDate() to show the month of the current Date object when it was being called.
So the issue is with your understanding of setDate that is being used on current. It changes the month and if the value you use isn't a day in the month it adjusts the month and day appropriately. I hope this cleared things up for you.
For how to add one to a date, see Add +1 to current date. Adapted to your code, you can set current to the first day of the week then just keep adding 1 day and pushing copies to the array:
function days(current) {
var week = [];
// Starting Monday not Sunday
var first = current.getDate() - current.getDay() + 1;
current.setDate(first);
for (var i = 0; i < 7; i++) {
week.push(new Date(+current));
current.setDate(current.getDate()+1);
}
return week;
}
var input = new Date(2017, 1, 27);
console.log('input: %s', input);
var result = days(input);
console.log(result.map(d => d.toString()));
Note that this changes the date passed in (per the original code), you may want to make current a copy to avoid that.
Suppose monday starts the week, you can calculate monday and go to sunday. getDategives you the day of the week, and Sunday starts at 0. With momnday, we get just offset forward to 6 days to get sunday
mondayThisWeek(date: Date): Date {
const d = new Date(date)
const day = d.getDay()
const diff = d.getDate() - day + (day === 0 ? -6 : 1)
return new Date(d.setDate(diff))
}
const offsetDate = (base: Date, count: number): Date => {
const date = new Date(base)
date.setDate(base.getDate() + count)
return date
}
thisWeek(today: Date): TimeRange {
const monday = mondayThisWeek(today)
return {
startDate: monday,
endDate: offsetDate(monday, 6)
}
}
This can be achieved easly using moment
const getWeekDates = () => {
let weekDates = [];
for (let i = 0; i < 7; i++)
weekDates.push(moment().add(i, 'd'));
return weekDates;
};
console.log(getWeekDates());
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.22.2/moment.js"></script>

How to get first week number of the month - javascript

I am populating all the months in Dropdown list, and i am enabling up to current month and remain months will be disabled, like
var date = new Date();
var month = new Date().getMonth() + 1;
var weeknum=//getting week number of the month
var options = $('#ddlMonth option');
var values = $.map(options, function (option) {
return option.value;
});
for (var i = 0; i <= values.length; i++) {
if (i > month) {
$("#ddlMonth option[value=" + i + "]").attr('disabled', true);
}
}
$('#ddlMonth').val(month);
Now I want to disable month if current week of the current month is first week.
Date.prototype.getMonthWeek = function(){
var firstDay = new Date(this.getFullYear(), this.getMonth(), 1).getDay();
return Math.ceil((this.getDate() + firstDay)/7);
}
Demo
http://jsfiddle.net/ay10bmpm/
 
Ref
http://www.somethinghitme.com/2010/04/14/how-to-get-the-week-in-a-month-for-a-date-with-javascript/
function(){
var d = new Date();
d.setHours(0,0,0);
d.setDate(d.getDate()+4-(d.getDay()||7));
return Math.ceil((((d-new Date(d.getFullYear(),0,1))/8.64e7)+1)/7);
};
This will get you the week in year and from this is simple math. (maybe not so simple for 5 weeks per month).
Or you can get the number of the week function from this fiddle : http://jsfiddle.net/OlsonDev/5mXF6/1/ (works with 5 weeks, tested)

Categories

Resources