how to check time difference of two fields that use time pickers - javascript

I have two time pickers and I need to check if the time selected from start to end is within a correct range, i got the values difference checked, but the values returned is NaN. Time shown is as 8:00 PM to 10:00 PM etc.
<div class="col-md-2">
<label>Service Start</label>
<input class="form-control timepicker1" type="text" id="start_time" />
</div>
<div class="col-md-2">
<label>Service End</label>
<input class="form-control timepicker1" type="text" id="end_time" />
</div>

Likely not the best since handling times with AM and PM you need to do some more work, also you need to check if first_time < second_time.
What you do is convert hh:mm:ss in seconds than input seconds in new Date() and can get different outputs.
But it should give you an idea how it can be done. moment.js can make things a lot easier
var hm_1 = '09:00 PM';
var hm_2 = '12:00 PM';
var a = hm_1.split(/:| /); // split at : and " "
var b = hm_2.split(/:| /);
// convert hours and minutes into seconds
var sec_1 = a[0] * 60 * 60 + a[1] * 60;
var sec_2 = b[0] * 60 * 60 + b[1] * 60;
console.log("convert", hm_1, "and", hm_2, "in", "seconds", sec_1, sec_2);
var date = new Date();
var date = new Date((sec_2 - sec_1) * 1000); //use js new Date () can take s/h/... as input
var hh = date.getUTCHours(); //get hours
var mm = date.getUTCMinutes(); //get minutes
if (hh < 10) {hh = "0"+hh;}
if (mm < 10) {mm = "0"+mm;}
// convert to hh:mm (its a 24h format)
var timeString = hh+":"+mm;
console.log("result", timeString)

Related

how to get number of days from angularjs

how to get number of days between two dates but its not working i think my date format not correct but how to change date format and get number of days
$scope.ChangeDate = function () {
var oneDay = 24 * 60 * 60 * 1000;
var firstDate = $scope.Current.PlainnedStart;
var secondDate = $scope.Current.PlainnedEnd;
if (!angular.isUndefined(firstDate) && !angular.isUndefined(secondDate)) {
var diffDays = Math.round(Math.abs((firstDate.getTime() - secondDate.getTime()) / (oneDay)));
alert(diffDays);
$scope.Current.NOD = ++diffDays;
}
}
enter image description here
<input type="text" onchange="angular.element(this).scope().ChangeDate()"
id="date" ng-model="Current.PlainnedStart"
class="floating-label mdl-textfield__input" placeholder="">
you can use
<input class="form-control" ng-model="day1" ng-blur="getDate(day1)" type="text" readonly />
$scope.getDate= function (date) {
var dates = new Date();
console.log(dates);
}
you can easily manage with momentjs with date evens
var a = moment('2018-04-17T07:00:00.000Z');
var b = moment('2018-04-27T07:00:00.000Z');
var days = b.diff(a, 'days');
http://momentjs.com/
or with Javascript
var a = new Date("2018-04-17T07:00:00.000Z");
var b = new Date("2018-04-27T07:00:00.000Z");
var dayDif = (a - b) / 1000 / 60 / 60 / 24;
You should convert both dates into the JavaScript Date object. From what I can see, the inputs from both date inputs are in 'dd-mm-yyyy' format, and this will cause some problems if you try to directly convert it into the Date object. Instead, you should convert it to 'yyyy-mm-dd' before converting it to a date object.
Then, you can calculate the difference between both dates.
const str1 = '17-04-2019';
const str2 = '20-04-2019';
const toDate = dateStr => {
const parts = dateStr.split('-');
return new Date(parts[2], parts[1] - 1, parts[0]);
}
const diff = Math.floor((toDate(str2) - toDate(str1) ) / 86400000);
console.log(diff)
As mentioned in the previous answer above you can either split the string to get the values. Or change it like below
Ex:Suppose my date string is
var str1 = '17-Apr-2019';
var str2 = '20-Apr-2019';
var diff = Math.abs(new Date(str2).getDate() - new Date(str1).getDate());
console.log(diff)
Output => 3
Or if you dont want any code changes.
Change the format of the datepicker to (mm-dd-yyyy) you will get same output

Timestamp calculated from the current time instead the source date

I want to add 30 days to a Date (including the timestamp), however, the timestamp is being calculated from the execution time of the script instead of the source data (loadStartDateTime).
I created a new date object and then set the date (purge_date = loadStartDateTime + 30days).
I saw an example doing some math with the dates, should I make the calculations of the timestamp separately?
PURGEDATE = (function (loadTime) {
var loadDate = new Date(loadTime);
var purge_date = new Date();
purge_date.setDate(loadDate.getDate()+30);
var month = purge_date.getMonth() + 1;
var mm = month < 10 ? "0" + month : month;
var day = purge_date.getDate();
var dd = day < 10 ? "0" + day : day;
var hours = purge_date.getHours() < 10 ? "0" + purge_date.getHours() : purge_date.getHours();
var minutes = purge_date.getMinutes() < 10 ? "0" + purge_date.getMinutes() : purge_date.getMinutes();
var seconds = purge_date.getSeconds() < 10 ? "0" + purge_date.getSeconds() : purge_date.getSeconds();
var time = hours + ":" + minutes + ":" + seconds;
var yyyy = purge_date.getFullYear();
return mm + "/" + dd + "/" + yyyy + time;
})(LoadStartDateTime)
The Result:
loadStartDateTime | PurgeDate
8/7/2018 5:55:45 PM | 09/06/2018 10:28:49
8/7/2018 5:58:10 PM | 09/06/2018 10:28:49
I saw an example doing some math with the dates, should I make the calculations of the timestamp separately?
Thank you~
After further investigation I realized that:
The Date object’s constructor is ISO 8601
When I use getDate() I do not provide the timezone explicitly.
This causes the timestamp to be 00:00:00 local time, so I should use getTime() method instead to get the timestamp. Since in JavaScript a timestamp is the number of milliseconds, a simple way to get it done is to send the timestamp value in the Date constructor. To calculate 30 days measured in timestamp:
30 * 24 * 60 * 60 * 1000
Finally, sum both values and send the result as a param in the constructor:
For example:
loadStartDateTime = new Date('8/7/2018 5:55:45 PM');
test_date = loadStartDateTime.getTime() + (30 * 24 * 60 * 60 * 1000);
test_date = new Date(test_date);
and then can continue with the Date Formatting.
I found the solution combining the answers from ISO 8601 date format - Add day with javascript and Add 30 days to date (mm/dd/yy). This guide "The Definitive Guide to DateTime Manipulation" helped to find out when I was wrong by understanding more about DateTime Manipulation.

Get the time elapsed between two timestamps and convert it to date [duplicate]

I know I can do anything and some more envolving Dates with momentjs. But embarrassingly, I'm having a hard time trying to do something that seems simple: geting the difference between 2 times.
Example:
var now = "04/09/2013 15:00:00";
var then = "04/09/2013 14:20:30";
//expected result:
"00:39:30"
what I tried:
var now = moment("04/09/2013 15:00:00");
var then = moment("04/09/2013 14:20:30");
console.log(moment(moment.duration(now.diff(then))).format("hh:mm:ss"))
//outputs 10:39:30
I do not understand what is that "10" there. I live in Brazil, so we are utc-0300 if that is relevant.
The result of moment.duration(now.diff(then)) is a duration with the correct internal values:
days: 0
hours: 0
milliseconds: 0
minutes: 39
months: 0
seconds: 30
years: 0
So, I guess my question is: how to convert a momentjs Duration to a time interval? I sure can use
duration.get("hours") +":"+ duration.get("minutes") +:+ duration.get("seconds")
but i feel that there is something more elegant that I am completely missing.
update
looking closer, in the above example now is:
Tue Apr 09 2013 15:00:00 GMT-0300 (E. South America Standard Time)…}
and moment(moment.duration(now.diff(then))) is:
Wed Dec 31 1969 22:39:30 GMT-0200 (E. South America Daylight Time)…}
I am not sure why the second value is in Daylight Time (-0200)... but I am sure that i do not like dates :(
update 2
well, the value is -0200 probably because 31/12/1969 was a date where the daylight time was being used... so thats that.
This approach will work ONLY when the total duration is less than 24 hours:
var now = "04/09/2013 15:00:00";
var then = "04/09/2013 14:20:30";
moment.utc(moment(now,"DD/MM/YYYY HH:mm:ss").diff(moment(then,"DD/MM/YYYY HH:mm:ss"))).format("HH:mm:ss")
// outputs: "00:39:30"
If you have 24 hours or more, the hours will reset to zero with the above approach, so it is not ideal.
If you want to get a valid response for durations of 24 hours or greater, then you'll have to do something like this instead:
var now = "04/09/2013 15:00:00";
var then = "02/09/2013 14:20:30";
var ms = moment(now,"DD/MM/YYYY HH:mm:ss").diff(moment(then,"DD/MM/YYYY HH:mm:ss"));
var d = moment.duration(ms);
var s = Math.floor(d.asHours()) + moment.utc(ms).format(":mm:ss");
// outputs: "48:39:30"
Note that I'm using the utc time as a shortcut. You could pull out d.minutes() and d.seconds() separately, but you would also have to zeropad them.
This is necessary because the ability to format a duration objection is not currently in moment.js. It has been requested here. However, there is a third-party plugin called moment-duration-format that is specifically for this purpose:
var now = "04/09/2013 15:00:00";
var then = "02/09/2013 14:20:30";
var ms = moment(now,"DD/MM/YYYY HH:mm:ss").diff(moment(then,"DD/MM/YYYY HH:mm:ss"));
var d = moment.duration(ms);
var s = d.format("hh:mm:ss");
// outputs: "48:39:30"
Your problem is in passing the result of moment.duration() back into moment() before formatting it; this results in moment() interpreting it as a time relative to the Unix epoch.
It doesn't give you exactly the format you're looking for, but
moment.duration(now.diff(then)).humanize()
would give you a useful format like "40 minutes". If you're really keen on that specific formatting, you'll have to build a new string yourself. A cheap way would be
[diff.asHours(), diff.minutes(), diff.seconds()].join(':')
where var diff = moment.duration(now.diff(then)). This doesn't give you the zero-padding on single digit values. For that, you might want to consider something like underscore.string - although it seems like a long way to go just for a few extra zeroes. :)
var a = moment([2007, 0, 29]);
var b = moment([2007, 0, 28]);
a.diff(b, 'days') //[days, years, months, seconds, ...]
//Result 1
Worked for me
See more in
http://momentjs.com/docs/#/displaying/difference/
If you want difference of two timestamp into total days,hours and minutes only, not in months and years .
var now = "01/08/2016 15:00:00";
var then = "04/02/2016 14:20:30";
var diff = moment.duration(moment(then).diff(moment(now)));
diff contains 2 months,23 days,23 hours and 20 minutes. But we need result only in days,hours and minutes so the simple solution is:
var days = parseInt(diff.asDays()); //84
var hours = parseInt(diff.asHours()); //2039 hours, but it gives total hours in given miliseconds which is not expacted.
hours = hours - days*24; // 23 hours
var minutes = parseInt(diff.asMinutes()); //122360 minutes,but it gives total minutes in given miliseconds which is not expacted.
minutes = minutes - (days*24*60 + hours*60); //20 minutes.
Final result will be : 84 days, 23 hours, 20 minutes.
When you call diff, moment.js calculates the difference in milliseconds.
If the milliseconds is passed to duration, it is used to calculate duration which is correct.
However. when you pass the same milliseconds to the moment(), it calculates the date that is milliseconds from(after) epoch/unix time that is January 1, 1970 (midnight UTC/GMT).
That is why you get 1969 as the year together with wrong hour.
duration.get("hours") +":"+ duration.get("minutes") +":"+ duration.get("seconds")
So, I think this is how you should do it since moment.js does not offer format function for duration. Or you can write a simple wrapper to make it easier/prettier.
This should work fine.
var now = "04/09/2013 15:00:00";
var then = "02/09/2013 14:20:30";
var ms = moment(now,"DD/MM/YYYY HH:mm:ss").diff(moment(then,"DD/MM/YYYY HH:mm:ss"));
var d = moment.duration(ms);
console.log(d.days() + ':' + d.hours() + ':' + d.minutes() + ':' + d.seconds());
If we want only hh:mm:ss, we can use a function like that:
//param: duration in milliseconds
MillisecondsToTime: function(duration) {
var seconds = parseInt((duration/1000)%60)
, minutes = parseInt((duration/(1000*60))%60)
, hours = parseInt((duration/(1000*60*60))%24)
, days = parseInt(duration/(1000*60*60*24));
var hoursDays = parseInt(days*24);
hours += hoursDays;
hours = (hours < 10) ? "0" + hours : hours;
minutes = (minutes < 10) ? "0" + minutes : minutes;
seconds = (seconds < 10) ? "0" + seconds : seconds;
return hours + ":" + minutes + ":" + seconds;
}
Use this:
var duration = moment.duration(endDate.diff(startDate));
var aa = duration.asHours();
Instead of
Math.floor(duration.asHours()) + moment.utc(duration.asMilliseconds()).format(":mm:ss")
It's better to do
moment.utc(total.asMilliseconds()).format("HH:mm:ss");
This will work for any date in the format YYYY-MM-DD HH:mm:ss
const moment=require("moment");
let startDate=moment("2020-09-16 08:39:27");
const endDate=moment();
const duration=moment.duration(endDate.diff(startDate))
console.log(duration.asSeconds());
console.log(duration.asHours());
In ES8 using moment, now and start being moment objects.
const duration = moment.duration(now.diff(start));
const timespan = duration.get("hours").toString().padStart(2, '0') +":"+ duration.get("minutes").toString().padStart(2, '0') +":"+ duration.get("seconds").toString().padStart(2, '0');
Typescript: following should work,
export const getTimeBetweenDates = ({
until,
format
}: {
until: number;
format: 'seconds' | 'minutes' | 'hours' | 'days';
}): number => {
const date = new Date();
const remainingTime = new Date(until * 1000);
const getFrom = moment([date.getUTCFullYear(), date.getUTCMonth(), date.getUTCDate()]);
const getUntil = moment([remainingTime.getUTCFullYear(), remainingTime.getUTCMonth(), remainingTime.getUTCDate()]);
const diff = getUntil.diff(getFrom, format);
return !isNaN(diff) ? diff : null;
};
DATE TIME BASED INPUT
var dt1 = new Date("2019-1-8 11:19:16");
var dt2 = new Date("2019-1-8 11:24:16");
var diff =(dt2.getTime() - dt1.getTime()) ;
var hours = Math.floor(diff / (1000 * 60 * 60));
diff -= hours * (1000 * 60 * 60);
var mins = Math.floor(diff / (1000 * 60));
diff -= mins * (1000 * 60);
var response = {
status : 200,
Hour : hours,
Mins : mins
}
OUTPUT
{
"status": 200,
"Hour": 0,
"Mins": 5
}
The following approach is valid for all cases (difference between dates less than 24 hours and difference greater than 24 hours):
// Defining start and end variables
let start = moment('04/09/2013 15:00:00', 'DD/MM/YYYY hh:mm:ss');
let end = moment('04/09/2013 14:20:30', 'DD/MM/YYYY hh:mm:ss');
// Getting the difference: hours (h), minutes (m) and seconds (s)
let h = end.diff(start, 'hours');
let m = end.diff(start, 'minutes') - (60 * h);
let s = end.diff(start, 'seconds') - (60 * 60 * h) - (60 * m);
// Formating in hh:mm:ss (appends a left zero when num < 10)
let hh = ('0' + h).slice(-2);
let mm = ('0' + m).slice(-2);
let ss = ('0' + s).slice(-2);
console.log(`${hh}:${mm}:${ss}`); // 00:39:30
This will return biggest time period diff like (4 seconds, 2 minutes, 1 hours, 2 days, 3 weeks, 4 months, 5 years).
I use this for notification recent time.
function dateDiff(startDate, endDate) {
let arrDate = ["seconds", "minutes", "hours", "days", "weeks", "months", "years"];
let dateMap = arrDate.map(e => moment(endDate).diff(startDate, e));
let index = 6 - dateMap.filter(e => e == 0).length;
return {
type: arrDate[index] ?? "seconds",
value: dateMap[index] ?? 0
};
}
Example:
dateDiff("2021-06-09 01:00:00", "2021-06-09 04:01:01")
{type: "hours", value: 3}
dateDiff("2021-06-09 01:00:00", "2021-06-12 04:01:01")
{type: "days", value: 3}
dateDiff("2021-06-09 01:00:00", "2021-06-09 01:00:10")
{type: "seconds", value: 10}
I create a simple function with typescript
const diffDuration: moment.Duration = moment.duration(moment('2017-09-04 12:55').diff(moment('2017-09-02 13:26')));
setDiffTimeString(diffDuration);
function setDiffTimeString(diffDuration: moment.Duration) {
const str = [];
diffDuration.years() > 0 ? str.push(`${diffDuration.years()} year(s)`) : null;
diffDuration.months() > 0 ? str.push(`${diffDuration.months()} month(s)`) : null;
diffDuration.days() > 0 ? str.push(`${diffDuration.days()} day(s)`) : null;
diffDuration.hours() > 0 ? str.push(`${diffDuration.hours()} hour(s)`) : null;
diffDuration.minutes() > 0 ? str.push(`${diffDuration.minutes()} minute(s)`) : null;
console.log(str.join(', '));
}
// output: 1 day(s), 23 hour(s), 29 minute(s)
for generate javascript https://www.typescriptlang.org/play/index.html
InTime=06:38,Outtime=15:40
calTimeDifference(){
this.start = dailyattendance.InTime.split(":");
this.end = dailyattendance.OutTime.split(":");
var time1 = ((parseInt(this.start[0]) * 60) + parseInt(this.start[1]))
var time2 = ((parseInt(this.end[0]) * 60) + parseInt(this.end[1]));
var time3 = ((time2 - time1) / 60);
var timeHr = parseInt(""+time3);
var timeMin = ((time2 - time1) % 60);
}
EPOCH TIME DIFFERENCE USING MOMENTJS:
To Get Difference between two epoch times:
Syntax:
moment.duration(moment(moment(date1).diff(moment(date2)))).asHours()
Difference in Hours:
moment.duration(moment(moment(1590597744551).diff(moment(1590597909877)))).asHours()
Difference in minutes:
moment.duration(moment(moment(1590597744551).diff(moment(1590597909877)))).asMinutes().toFixed()
Note: You could remove .toFixed() if you need precise values.
Code:
const moment = require('moment')
console.log('Date 1',moment(1590597909877).toISOString())
console.log('Date 2',moment(1590597744551).toISOString())
console.log('Date1 - Date 2 time diffrence is : ',moment.duration(moment(moment(1590597909877).diff(moment(1590597744551)))).asMinutes().toFixed()+' minutes')
Refer working example here:
https://repl.it/repls/MoccasinDearDimension
To get the difference between two-moment format dates or javascript Date format indifference of minutes the most optimum solution is
const timeDiff = moment.duration((moment(apptDetails.end_date_time).diff(moment(apptDetails.date_time)))).asMinutes()
you can change the difference format as you need by just replacing the asMinutes() function
If you want a localized number of days between two dates (startDate, endDate):
var currentLocaleData = moment.localeData("en");
var duration = moment.duration(endDate.diff(startDate));
var nbDays = Math.floor(duration.asDays()); // complete days
var nbDaysStr = currentLocaleData.relativeTime(returnVal.days, false, "dd", false);
nbDaysStr will contain something like '3 days';
See https://momentjs.com/docs/#/i18n/changing-locale/ for information on how to display the amount of hours or month, for example.
It is very simple with moment
below code will return diffrence in hour from current time:
moment().diff('2021-02-17T14:03:55.811000Z', "h")
const getRemainingTime = (t2) => {
const t1 = new Date().getTime();
let ts = (t1-t2.getTime()) / 1000;
var d = Math.floor(ts / (3600*24));
var h = Math.floor(ts % (3600*24) / 3600);
var m = Math.floor(ts % 3600 / 60);
var s = Math.floor(ts % 60);
console.log(d, h, m, s)
}

javascript how to check number of days in between 2 dates [duplicate]

This question already has answers here:
Get difference between 2 dates in JavaScript? [duplicate]
(5 answers)
Closed 5 years ago.
i am working on a date test javascript program that will let the user enter a date. It will parse the date to display the Month, day and year on separate lines with appropriate labels. It will also compare the current date with the entered date to display the number of day difference between them. So far I have been able to get the current dat to display and take users input but do not know how to calculate the number of days inbetween against the date I input. For some reason it is using the year 1969 I think to give me number of days difference and can not get it to parse into seperate lines. Have been working on this for weeks and is breaking my head on different ways to do so. So far I have the following:
<header>
<h1>Date Test</h1>
</header>
<br>
<p>Please enter date:</p>
<input id="inp" type="date">
<br>
<br>
<button type="button" onclick="date_test()">Process</button>
<br>
<p id="iop"></p>
<br>
<p id="op"></p>
<br>
<p id="dd"></p>
<script>
document.getElementById("op").innerHTML = Date();
function date_test() {
var d = document.getElementById("inp").value;
document.getElementById("iop").innerHTML = d;
var inpu = document.getElementById("inp").value;
var da = Date.parse(inpu);
var minutes = 1000 * 60;
var hours = minutes * 60;
var days = hours * 24;
var x = Math.round(da / days);
document.getElementById("dd").innerHTML = x;
}
</script>
Here is sample code
<header>
<h1>Date Test</h1>
</header>
<br>
<p>Please enter date:</p>
<input id="inp" type="date">
<br>
<br>
<button type="button" onclick="date_test()">Process</button>
<br>
<p id="iop"></p>
<br>
<p id="op"></p>
<br>
<p id="dd"></p>
<script>
document.getElementById("op").innerHTML = Date();
function date_test() {
var d = document.getElementById("inp").value;
document.getElementById("iop").innerHTML = d;
var inpu = document.getElementById("inp").value;
var da = Date.parse(inpu);
//here passing current date & selected date as params
console.log(daysBetween(new Date(), new Date(da)))
}
daysBetween = function( date1, date2 ) {
console.log(date1);
console.log(date2);
//Get 1 day in milliseconds
var one_day=1000*60*60*24;
// Convert both dates to milliseconds
var date1_ms = date1.getTime();
var date2_ms = date2.getTime();
// Calculate the difference in milliseconds
var difference_ms = date2_ms - date1_ms;
// Convert back to days and return
return Math.round(difference_ms/one_day);
}
</script>
Here is a simple function that you can use
function calculate_days(date1, dat2){
return (date2-date1)/(24*3600*1000);
}
date1 = new Date("4-4-2017");
date2 = new Date("4-8-2017");
console.log(calculate_days(date1, date2));
where date1 and date2 are date objects. 1000 in the denominator is needed as the difference would return number of milliseconds.
var date1 = new Date();
var dd = date1.getDate()+20; // add 20 days
var mm = date1.getMonth()+1; //January is 0!
var yyyy = date1.getFullYear();
if(dd<10) {
dd='0'+dd
}
if(mm<10) {
mm='0'+mm
}
date2 = new Date(yyyy+'/'+mm+'/'+dd);
var timeDiff = Math.abs(date2.getTime() - date1.getTime());
days = Math.ceil(timeDiff / (1000 * 3600 * 24));
console.log("day difference: ", days);
i think you should use these code
var date1 = new Date("7/20/2017");
var date2 = new Date("12/25/2017");
var timeDiff = Math.abs(date2.getTime() - date1.getTime());
var diffDays = Math.ceil(timeDiff / (1000 * 3600 * 24));
alert(diffDays);

Javascript Adding Time for a Future Date

I looked at some other questions, and don't see my specific problem, so please excuse me if it has been asked or answered.
What I am trying to do is figure out a simple "payment" calculator, and provide some additional information, such as the first payment date, and the last.
In some cases, the day of the last payment works, and sometimes it doesn't.
Here's my code:
var myDate = new Date();
var odo = document.contract.firstPaymentDate.value;
var n = odo.split("/");
var month = n[0];
var day = n[1];
var year = n[2];
var oldDateObj = new Date(year, month, day);
var newDateObj = new Date(oldDateObj.getTime() + ((document.contract.totalNumberRegularPayments.value - 1)*1209600*1000));
var dd = newDateObj.getDate();
var mm = newDateObj.getMonth();
var y = newDateObj.getFullYear();
var someFormattedDate = mm + '/'+ dd + '/'+ y;
document.contract.lastPaymentDate.value = someFormattedDate;
So I take the first payment date, and add 1209600 seconds times the number of payments (minus 1 since they have "already" paid the first).
This is based on starting at a specific day that can be chosen by the user.
So my example is 156 BiWeekly payments (so 155 for the calculations), which works out to 6 years. If I choose the date of the 1st, I get 10/01/2013 as the start, but 9/11/2019 as the end (First on a Tuesday, last on a Wednesday).
For the 15th (9/15/2013 - a Sunday - to 8/24/2019 - a Saturday)
For the 20th (9/20/2013 - a Friday - to 8/29/2013 - a Thursday)
So since sometimes it's a day later, and sometimes a day ahead, I can't just +1 to var dd = newDateObj.getDate();
I'm really baffled as to what's going on, and I'm hoping someone out there either has some experience with this, or someone that knows what the heck I might be doing wrong.
Thanks in advance for any help you can offer.
If you want to add a number of weeks, just add 7 times as many days, e.g.
var now = new Date();
// Add two weeks
now.setDate(now.getDate() + 14);
So if you have 24 fortnightly payments:
var now = new Date();
// Add 24 fortnights (48 weeks)
now.setDate(now.getDate() + 24 * 14);
or
now.setDate(now.getDate() + 24 * 2 * 7);
whatever you think is clearest.
If you want to have a start and end date:
var start = new Date();
var end = new Date(+start);
end.setDate(end.getDate() + 24 * 14);
alert('Start on: ' + start + '.\nEnd in 24 fortnights: ' + end);
Edit
Here's a working example:
<script>
function calcLastPayment(start, numPayments) {
if (typeof start == 'string') {
start = stringToDate(start);
}
var end = new Date(+start);
end.setDate(end.getDate() + --numPayments * 14)
return end;
}
// Expect date in US format m/d/y
function stringToDate(s) {
s = s.split(/\D/)
return new Date(s[2], --s[0], s[1])
}
</script>
<form>
<table>
<tr><td>Enter first payment date (m/d/y):
<td><input name="start">
<tr><td>Enter number of payments:
<td><input name="numPayments">
<tr><td colspan="2"><input type="button" value="Calc end date" onclick="
this.form.end.value = calcLastPayment(this.form.start.value, this.form.numPayments.value)
">
<tr><td>Last payment date:
<td><input readonly name="end">
<tr><td colspan="2"><input type="reset">
</table>
</form>
Given a first payment date of Thursday, 5 September and 3 repayments it returns Thursday 3 October, which seems correct to me (5 and 19 September and 3 October). It should work for any number of payments.
There is a simple way to do this in a line or two of code.
I use 864e5 for the number of milliseconds in a day. Because 1000 milliseconds/second * 60 seconds/minute * 60 minutes/hour * 24 hours/day = 86400000 milliseconds/day or 864e5.
var now = new Date,
day = 864e5,
weekFromNow = new Date(+now + day * 7); //+now casts the date to an integer
+now casts the date to an integer, the number of milliseconds. now.valueOf() works too.
day * 7 or 864e5 * 7 is the number of milliseconds in a week.
new Date(...) casts the number of milliseconds to a date again.
Sometimes you don't have to worry about casting the value back to a date.

Categories

Resources