This question already has answers here:
Incrementing a date in JavaScript
(19 answers)
Closed 6 years ago.
I have this script;
showDiff();
function showDiff() {
var date1 = new Date("2016/03/14 00:00:00");
var date2 = new Date();
var diff = (date2 - date1);
var diff = Math.abs(diff);
var result;
if (diff > 432000000) {
result = 100 + "%";
} else {
result = (diff/4320000) + "%";
}
document.getElementById("showp").innerHTML = result;
document.getElementById("pb").style.width = result;
setTimeout(showDiff,1000);
}
Now I want to get exactly one week added to date1 when atleast one week has passed since that time. That date has to be saved so that one week later, another week can be added to date1. So basically every monday there has to be one week added to date1. How do I this?
The Date object has both a getDate() and setDate() function (date referring to the day of the month, no the full calendar date), so it's really as simple as getting a Date object and setting its date to +7 days from itself.
Example:
var weekFromNow = new Date();
weekFromNow = weekFromNow.setDate(weekFromNow.getDate()+7);
Just to clarify, the Date object contains a full calendar date and time, with its date property referring just to the day in the month (also different from its day property, which is the day of the week).
Related
This question already has answers here:
setDate() returns number 1603240915215 instead of a date
(2 answers)
Closed 2 years ago.
I a trying to save a date to the nextMonth. For that I am first setting the month to next 30 days. But the final output date it is giving me in milliseconds.
I want the date in GMT format strictly.
What can I do for that?
var snm = new Date();
snm = snm.setDate(snm.getDate() + 30);
console.log("snm = "+ snm);
Try this
var snm = new Date();
snm.setDate(snm.getDate() + 30)
console.log("snm = "+ snm.toString());
In node.js I need to get the date within the date range of particular gap.
Consider two dates:
startDate:2016-07-10T00:00:00.000Z,
payByDate:"13"(13th of every month);
endDate:2016-10-08T00:00:00.000Z
I need an array of dates of monthly or weekly gap between these 2 dates.
My result Should be:(Monthly gap)
[2016-07-13T00:00:00.000Z,
2016-08-13T00:00:00.000Z,
2016-09-13T00:00:00.000Z]
EDIT:
My startdate is 2016-07-10T00:00:00.000Z , so i can calculate the noOfmonths using endDate-startdate, but the array entry should be by payByDate.
I am using MOMENT.JS, but its returning only noOfMonths not the dates. Please share your ideas. Thanks in advance.
Now is it possible to calculate the calculate the Above array.Please note that "payByDate" is string.
you can use getMonth() function to get the month of your date. then keep adding one to it till you reach the end date.
var arrayDates = [];
arrayDates.push(startDate);
var tempDate = new Date(new Date(startDate).setMonth(startDate.getMonth()+1));
while(tempDate < endDate)
{
arrayDates.push(tempDate);
var tempDate = new Date(new Date(tempDate).setMonth(tempDate.getMonth()+1));
}
Abouve logic will work for monthly gap. to get array of weekly gap, use getDate() function and keep adding 7 to it till you reach the end Date
Try using the manipulate method in moment.js to add a month to the starting date until you reach the second date.
Consider this code. Assuming that the first date and the last date are already moments when they are passed into this function, you can use the diff and manipulate methods to create an array of dates by month in between the two different dates:
EDIT:
function monthsBetween(payByDate, startDate, lastDate) {
var months = [];
//finds nearest date to the start date that is on the payByDate
var currentDate = startDate.date(parseInt(payByDate));
//checks if the date is after the startDate and adds a month if it is
if(!currentDate.isSameOrAfter(startDate)){
currentDate = currentDate.add(1, 'months');
}
while (currentDate.isSameOrBefore(lastDate)) {
months.push(currentDate);
currentDate = currentDate.add(1, 'months');
}
return months;
}
I really need some assistance with a time calculation in JS.
Put basically I need to calculate how many times a day of a month has occurred between two dates.
For Example -
A date of 15th of the month between 1st February 2014 to 14 May 2014 would be 3
A date of 15th of the month between 1st February 2014 to 16 May 2014 would be 4
I've looked at moment Jquery library but it estimates that a month is 30 days so I wouldn't be exact and take into consideration leap years - months with 28 days etc..
It really needs to be exact because its for a chargeable event calculation. The dates can spare many years so could lead to in-accuries because of the 30 day thing.
Any help would be appreciated
There are probably a million ways to do this... here's a brute force way:
// add a "addDays() method to Date"
Date.prototype.addDays = function(days)
{
var dat = new Date(this.valueOf());
dat.setDate(dat.getDate() + days);
return dat;
}
// provide two dates and a day ordinal you want to count between the two
function numOrdinalsBetweenDts(Date1, Date2, theOrdinal) {
var temp;
if(Date2 < Date1) { // put dates in the right order (lesser first)
temp = Date1;
Date1 = Date2;
Date2 = temp;
}
var workDate = Date1;
var ctr = 0;
while(workDate < Date2) { // iterate through the calendar until we're past the end
if(workDate.getDate() == theOrdinal) // if we match the ordinal, count it
ctr++;
workDate = workDate.addDays(1); // move the calendar forward a day
}
return ctr;
}
var result = numOrdinalsBetweenDts(new Date("July 21, 1901"), new Date("July 21, 2014"), 2);
console.log(result);
alert(result);
There is a slightly counter-intuitive behavior in the Javascript Date constructor where if you create a new Date with the day set to 0, it will assume the last day of the month. You can the use the following function get the number of days in a month:
function daysInMonth(month, year) {
return new Date(year, month, 0).getDate();
}
The Javascript date object is leap-year aware, so you can use this function reliably.
You then just need to count the number of months between the start and end date and check each one to make sure the day number is actually present in the month. You can short-circuit this check if the day is less than or equal to 28.
This question already has answers here:
JavaScript date objects UK dates
(6 answers)
Closed 9 years ago.
I have the below code. If we try to retrieve the day, month and year in UK server setup. The date object returns an incorrect value.
var startDate = "30/08/2013";
var d = new Date(startDate);
alert(d.getFullYear()); //2015
Please help me
Use moment.js if you want better control of parsing:
var startDate = "30/08/2013";
var m = moment(startDate,"DD/MM/YYYY");
alert(m.year()); //2013
Try passing the date as a list of arguments instead:
var startDate = "30/08/2013"; // Would also work with 30-08-2013
var startDateArray;
if(startDate.contains('/'))
startDateArray = startDate.split('/');
else if (startDate.contains('-'))
startDateArray = startDate.split('-');
else if (startDate.contains('.'))
startDateArray = startDate.split('.');
var d = new Date(startDateArray[2], startDateArray[1]-1, startDateArray[0]); // Month is 0 based, that's why we are subtracting 1
I would like to have an input field with a button next to it.
On the input field I will enter a date like this:
2011-07-08
And when I hit the button it should read the time that has been entered on the input field and subtract it with 3 months and one day.
Is this possible?
Thanks in advance
Yes. First you read the date and you convert to a date object
var dateString = document.getElementById('id of your field').value,
date = new Date(dateString);
then you subtract 91 days and output the result
date.setDate(date.getDate() - 91);
alert(date.toString());
Here I assume for simplicity that you actually want 91 days and not 3 months and one day. If you want three months and one day you will do
date.setMonth(date.getMonth() - 3);
date.setDate(date.getDate() - 1);
alert(date.toString());
The Date object will take care of overflows, leap years and everything.
If you want to write it to same field, taking care of zeroes, you can do
function assureTwoDigits(number) {
if (number > 9) {
return '-' + number;
}
else {
return '-0' + number;
}
}
and change the last line to
document.getElementById('id of your field').value = date.getFullYear() + assureToDigits(date.getMonth()) + assureTwoDigits(date.getDate());
You can use Date objects (see here):
extract year, moth and day from the string (using a regular expression or splitting by '-')
buid a new Date object with that data
subtract the date interval
build the string back
The simplest way would be to split it into an array, then use a couple of if/else statements:
var date = (whatever you're pulling the date in as).split('-');
if (date[1] > 3)
date[1] = date[1] - 3;
else
date[0] = date[0] - 1;
var dateOverflow = date[1]-3;
date[1] = 12 - dateOverflow;
And then the same for the days.
Yes, it's possible and it's the most clean if you can do it without some arcane regex magic. Start by converting the date to a Date object:
// this will get you a date object from the string:
var myDate = new Date("2011-07-08");
// subtract 3 months and 1 day
myDate.setMonth(myDate.getMonth()-3);
myDate.setDay(myDate.getMonth(), myDate.getDay()-1);
// And now you have the day and it will be correct according to the number of days in a month etc
alert(myDate);