Change date range in javascript - javascript

I am trying to set start and end date in date picker where start date is week before current date and end date is week after start date. In certain condition it gives me 0 for start date. Can anyone look into code below and help me to get proper date range when current date is first day of the month or last date of the month. Thanks for your help.
var date = new Date();
//When current date was less then 7 in some situation it giving me error. So, I am checking current date and randomly subtract 3.
//if current date is less then 7 then get the last day of the previous month
if (date.getDate() <= 7) {
day = new Date(date.getFullYear(), date.getMonth(), 0);
startdate = day.getDate() - 3;
month = day.getMonth() + 1;
year = day.getFullYear();
if (month < 10) month = "0" + month;
if (day < 10) day = day;
console.log("App Config: lasy day: " + startdate + "\nmonth: " + month + "\nyear:" + year);
}
else {
startdate = date.getDate() - 7;
month = date.getMonth() + 1;
year = date.getFullYear();
if (month < 10) month = "0" + month;
if (day < 10) day = day;
console.log("App Config: day: " + startdate + "\nmonth: " + month + "\nyear:" + year);
}
return month + "/" + startdate + "/" + year;

Have you tried this:
var dt = new Date();
var weekBefore = dt.setDate(dt.getDate() - 7);
var weekAfter = dt.setDate(dt.getDate() + 7);
JavaScript will figure it out automatically the date 7 days before and after!

If you are ok with plugins I would suggest Moment.js which is great for date handling. Adding a week would be as easy as
var inOneWeek = moment().add(1, 'weeks');//.format('DD/MM/YYYY'); if u want it in DD/MM/YYYY format
var oneWeekAgo = moment().add(-1, 'weeks');//.format('DD/MM/YYYY');
otherwise #sabotero's answer would do as well.

Related

Add future days to Javascript excluding on sunday

I have the following javascript code that allows a user to only select four days in future from today's date.
$(function() {
var dtToday = new Date();
var month = dtToday.getMonth() + 1;
if (dtToday.getDay() === 0) {
var day = dtToday.getDate() + 5;
} else {
var day = dtToday.getDate() + 4;
}
var year = dtToday.getFullYear();
if (month < 10)
month = '0' + month.toString();
if (day < 10)
day = '0' + day.toString();
var maxDate = year + '-' + month + '-' + day;
$('.datepicker').attr('max', maxDate);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
I would like the code to skip Sunday while incrementing the future days by four. I have tried using if statements but they only check if today's date is sunday while i would like to achieve a situation whereby if any of the future 4 days is Sunday, it should skip it.
Thanks
If today is Wednesday (3), Thursday (4), Friday (5), or Saturday (6), then your 4-day window would include Sunday (hence you should add 1 to days).
So do this:
var day = dtToday.getDate() + 4;
if(dtToday.getDay() > 2) {
day += 1;
}
So your script would be:
$(function(){
var dtToday = new Date();
var month = dtToday.getMonth() + 1;
var day = dtToday.getDate() + 4;
if(dtToday.getDay() > 2) {
day += 1;
}
var year = dtToday.getFullYear();
if(month < 10)
month = '0' + month.toString();
if(day < 10)
day = '0' + day.toString();
var maxDate = year + '-' + month + '-' + day;
$('.datepicker').attr('max', maxDate);
});

Javascript get start of the month

How to get the start of the month in date format e.g. 01-05-2017?
I have already seen
Get first and last date of current month with javascript or jquery
If I understand correctly toLocaleString() might do what you want.
For example:
lastDay.toLocaleString('en-GB', {day: 'numeric', month: '2-digit', year: 'numeric'});
For more info (MDN)
Replace locale with any that suits your desired formatting.
After getting the date we need to convert it to desired string format.
01 is the day and may be a constant since every beginning of the month starts from 1.
getMonth returns number of the month starting from 0 so we need a little function to format it.
var date = new Date();
var startDate = new Date(date.getFullYear(), date.getMonth(), 1);
var startDateString = '01-' + fotmatMonth(startDate.getMonth()) + '-' + startDate.getFullYear();
console.log(startDateString);
function fotmatMonth(month) {
month++;
return month < 10 ? '0' + month : month;
}
var date = new Date();
console.log(getStartOfMonthDateAsString(date));
function getStartOfMonthDateAsString() {
function zerosPad(number, numOfZeros) {
var zero = numOfZeros - number.toString().length + 1;
return Array(+(zero > 0 && zero)).join("0") + number;
}
var day = zerosPad(1, 2);
var month = zerosPad((date.getMonth() + 1), 2);
var year = date.getFullYear();
return day + '-' + month + '-' + year;
}

momentjs getting the week days of a target date

I'm using momentjs to work with dates, I get the current week using:
var startDate = moment().startOf('isoweek');
var endDate = moment().endOf('isoweek');
var weekDays = getWeekDays(startDate, endDate);
where the function getWeekDays is implemented as the follow:
function getWeeDays(startDate, endDate) {
"use strict";
var days = [];
var day = startDate;
while (day <= endDate) {
days.push(day);
day = day.clone().add(1, 'd');
}
return days;
}
This works pretty well, but now i need to get the days not of the current week but of the week of a target date.
For example the user input me the date 24/05/2016 and i need to get te days starting from Monday 23 May 2016 to Sunday 29 May 2016.
I have tried:
var startDate = moment().startOf('isoweek').year(year).month(month).day(day);
var endDate = moment().endOf('isoweek').year(year).month(month).day(day);
var weekDays = getWeekDays(startDate, endDate);
where the variable year, month and day are equals in this example to: 2016, 05, 24. This doesn't work. Do you have any suggestions using momentjs Or how to do it without using momentjs?
UPDATE
Ok I solved it myself! Sorry for the posted question, i put the solution here ( First check is the date is valid!):
if(moment(year + "/" + month + "/" + day, "YYYY/MM/DD", true).isValid()){
var startDate = moment(year + "/" + month + "/" + day, "YYYY/MM/DD").startOf('isoweek');
var endDate = moment(year + "/" + month + "/" + day, "YYYY/MM/DD").endOf('isoweek');
var weekDays = getWeekDays(startDate, endDate);
}
This is what i did to solve the problem:
if(moment(year + "/" + month + "/" + day, "YYYY/MM/DD", true).isValid()){
var startDate = moment(year + "/" + month + "/" + day, "YYYY/MM/DD").startOf('isoweek');
var endDate = moment(year + "/" + month + "/" + day, "YYYY/MM/DD").endOf('isoweek');
var weekDays = getWeekDays(startDate, endDate);
}
function getWeeDays(startDate, endDate) {
"use strict";
var days = [];
var day = startDate;
while (day <= endDate) {
days.push(day);
day = day.clone().add(1, 'd');
}
return days;
}
`moment(anyValidDate).day()`
// will return you the index of the day of given date.
//i.e. 0 for Sunday, 1 for Monday and so on till 6 for Saturday. list of week days.
new Date().getDay() // will give same result as above.
next you know what to do.

Date code not working in JS

I bet this is something really silly but I am tired and looking for a quick escape so please indulge me. Objective is to be able to add arbitrary days to a date constructed from a string like 2015-01-01.
firstDate = '2015-01-01';
var t1_date = new Date(firstDate);
t1_date.setTime( t1_date.getTime() + 90 * 86400000 );
lastDate = getFormattedDate(t1_date);
console.log("Two dates: ", firstDate, lastDate);
function getFormattedDate(date) {
var year = date.getFullYear();
var month = date.getMonth().toString();
month = month.length > 1 ? month : '0' + month;
var day = date.getDate().toString();
day = day.length > 1 ? day : '0' + day;
return year + '-' + month + '-' + day;
}
And then :
I get the output which is wrong because I am adding 90 days..
Two dates: 2015-01-01 2015-02-31
The problem lies in this line:
var month = date.getMonth().toString();
The function Date.getMonth() returns “the month (0-11) in the specified date according to local time”. January is 0, December is 11, so you need to add 1 to the output:
var month = "" + (date.getMonth()+1);
var month = date.getMonth().toString(); prints the no of months starting from no 0 so the month number is reduced by 1 for eg. the value of january from date.getMonth(); would be 0 and so on till 11.
here's the correct version for your code
firstDate = '2015-01-01';
var t1_date = new Date(firstDate);
console.log("before conversion");
console.log(t1_date);//before conversion
t1_date.setTime( t1_date.getTime() + 90 * 86400000 );
console.log("after conversion");
console.log(t1_date);//after conversion
lastDate = getFormattedDate(t1_date);
console.log("Two dates: ", firstDate, lastDate);
function getFormattedDate(date)
{
var year = date.getFullYear();
var month = date.getMonth();
var month1=(month+1).toString();
month1 = month1.length > 1 ? month1 : '0' + month1;
var day = date.getDate().toString();
day = day.length > 1 ? day : '0' + day;
return year + '-' + month1 + '-' + day;
}
Never parse strings with the Date constructor, always manually parse them. An ISO date without a timezone should be treated as local*, however ES5 said to treat it as UTC, then ECMAScript 2015 inferred to treat them as local (hooray for consistency) but then the implementors decided to treat them as UTC again, so browsers might do either (or NaN).
So the sensible thing is to manually parse them as local.
Outputting as a local ISO date is also fairly simple.
* Where local means per system settings.
function parseISODate(s) {
var b = s.split(/\D/);
var d = new Date(b[0], --b[1], b[2]);
return d && d.getMonth() == b[1]? d : new Date(NaN);
}
document.write(parseISODate('2015-01-01') + '<br>');
function toISODate(date) {
function z(n){return ('0'+n).slice(-2)}
return date.getFullYear() + '-' + z(date.getMonth() + 1) + '-' + z(date.getDate());
}
document.write(toISODate(parseISODate('2015-01-01')));
To add 90 days, it is simpler to just add 90 days to the date:
var d = new Date(2015,0,1); // 1 January 2015
d.setDate(d.getDate() + 90); // add 90 days
document.write(d.toLocaleString()); // 1 April 2015

get the month last date by adding 6 months to today's date

Iam adding 6 months to today's date by using below code.
var d = new Date();
var curr_date = d.getDate();
var curr_month = d.getMonth() + 7; //Months are zero based
if(curr_month<10){
curr_month = "0"+curr_month;
}
if(curr_date<10){
curr_date = '0'+curr_date;
}
var curr_year = d.getFullYear();
$scope.vmEndDate = curr_year + "/" + curr_month + "/" + curr_date;
When I print $scope.vmEndDate value, Iam getting 2015/09/31 , but in september month 31 day is not there. how to get correct value.
You can handle date with months directly :
var today = new Date(2015,03,31)
today.setMonth(today.getMonth()+6)
console.log(today.toLocaleDateString())
If you want to get a valid date but in september, https://stackoverflow.com/a/11469976/4682796
In the javascript world months begin with zero! kind of weird to me. Anyhow,adding 7 to date is NOT September, but rather 7 is October.
So that means your code is correct
Just change
var curr_month = d.getMonth() + 7; //Months are zero based
to
var curr_month = d.getMonth() + 6; //Months are zero based
Following code snippet might be helpful.
var d = new Date();
var curr_date = new Date(d.getFullYear(), d.getMonth() + 6, d.getDate());
console.log(curr_date.getFullYear() + "/" +
((curr_date.getMonth() + 1).toString().length == 1 ? '0' +
(curr_date.getMonth() + 1) : (curr_date.getMonth() + 1)) + "/" +
(curr_date.getDate().toString().length == 1 ? '0' +
(curr_date.getDate()) : (curr_date.getDate())));
}
Using code from this question this can be solved as follows.
You first get the todays date, change its day to first(or any number which is valid for all months like 1 to 28), then move ahead by six months and then set the date to last day of the month.
function daysInMonth(month, year)
{
return 32 - new Date(year, month, 32).getDate();
}
var today = new Date()
today.setDate(1)
today.setMonth(today.getMonth()+6)
today.setDate(daysInMonth(today.getMonth(), today.getDate()))

Categories