Time Difference between days [duplicate] - javascript

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Difference between dates in JavaScript
I've found myself at a javascript brick wall.
I would like to find the difference (in hours and minutes) between two times on two different days.
I can produce the hours, minutes and day of the week for each but cannot work out how to implement a function that will check how long there is until the next time.
Example:
If it's 16:00 on Friday and the next time is Monday at 13:00 the output would be 69 hours and 0 minutes.
Anyone got any ideas on how best to implement this?
N.B. I'm heavily using Google Closure.

var yourTimeStart = 'Friday 16:00'; //Your input
var yourTimeStop = 'Monday 13:00'; //Your input
var days = Array("Monday","Tuesday","Wednesday","Thursday","Friday","Saturday","Sunday");
var differenceDays = days.indexOf(yourTimeStop.split(" ")[0]) - days.indexOf(yourTimeStart.split(" ")[0]);
if (days.indexOf(yourTimeStart.split(" ")[0]) > days.indexOf(yourTimeStop.split(" ")[0])) differenceDays = differenceDays + 7;
var timeStart = yourTimeStart.split(" ")[1];
var timeStop = yourTimeStop.split(" ")[1];
var differenceHours = timeStop.split(":")[0] - timeStart.split(":")[0];
var differenceMins = timeStop.split(":")[1] - timeStart.split(":")[1]
var resultHours = differenceDays*24 + differenceHours;;
if (differenceMins < 0) {
resultHours--;
differenceMins = 60 + differenceMins; // differenceMins is negative
}
if (resultHours < 0) resultHours = resultHours + 7*24; //(this is if a you calculate the time between for example Monday 16:00 and Monday 12:00)
document.write(resultHours + " hour(s) and " + differenceMins + " minutes."); //output

For Example :
var dte = new DateTime(2012, 12, 26,1,0,0);
var dte2 = new DateTime(2012, 12, 27, 18, 5, 0);
var totalHours = (int) dte2.Subtract(dte).TotalHours;
var totalMin = dte2.AddHours(-totalHours).Subtract(dte).TotalMinutes;
Console.WriteLine(totalHours.ToString());
Console.WriteLine(totalMin.ToString());

Related

Multiple day(s) left javascript timer for multiple time zones

What I am trying to accomplish is multiple countdowns with different expiration dates. I have a code snippet from Codepen, I used as a starting point that works for just one countdown. I am also hoping that no matter whether the viewer is in California, or Georgia the expiration will know what the time zone is. I added the suggested getTimezoneOffset() to deal with different time zones. Which causes the countdown to multiply the days remaining to an absurd number that is 50 years in the future. When I remove that, it is fine. So I have not figured out how to implement that suggestion correctly. Through much trial and error I did successfully create a duplicate countdown with a different expiration date. The only thing I don't understand still is how to implement getTimezoneOffset() so that it does not display 17,893 and 17,883 days (50 years worth of days). I am a trial and error javascript modifier. I try stuff until something is no longer broken.
var countDownDate = new Date("DEC 27, 2018").getTime();
var countDownDate2 = new Date("DEC 17, 2018").getTime();
// COPY FEED
var data = {
// OFFER 1
one: "Offer One",
two: "Free Product",
three: "Today Only",
// OFFER 2
four: "Offer Two",
five: "Free Pickup",
six: "<span id='daysLeft'></span> <span id='plural'></span>",
seven: "Expires: Dec. 27, 2018",
// OFFER 3
eight: "Offer Three",
nine: "<span id='daysLeft2'></span> <span id='plural2'></span>",
ten: "Expires: Dec. 17, 2018",
};
// LOOP THROUGH KEYS TO GET ALL ELEMENT IDs & CREATE VARIABLES
function bannerFunc() {
for (key in data) {
if (data.hasOwnProperty(key)) {
var value = data[key];
var key = document.getElementById('" + key + "');
}
}
// ASSIGN OBJECT VALUES TO VARIABLES
one.innerHTML = data.one;
two.innerHTML = data.two;
three.innerHTML = data.three;
four.innerHTML = data.four;
five.innerHTML = data.five;
six.innerHTML = data.six;
seven.innerHTML = data.seven;
eight.innerHTML = data.eight;
nine.innerHTML = data.nine;
ten.innerHTML = data.ten;
// DATE CODE
var x = setInterval(function() {
var now = new Date().getTimezoneOffset(),
amountLeft = countDownDate - now,
days = Math.floor(amountLeft / (1000 * 60 * 60 * 24) + 1),
plural = document.getElementById('plural');
plural.innerHTML = days + ' Days Left';
if( days < 2 && days > 0 ){
plural.innerHTML = days + ' Day Left';
}
if( days <= 0 ){
plural.innerHTML = 'Expired';
}
var now = new Date().getTimezoneOffset(),
amountLeft = countDownDate2 - now,
days = Math.floor(amountLeft / (1000 * 60 * 60 * 24) + 1),
plural = document.getElementById('plural2');
plural2.innerHTML = days + ' Days Left';
if( days < 2 && days > 0 ){
plural2.innerHTML = days + ' Day Left';
}
if( days <= 0 ){
plural2.innerHTML = 'Expired';
}
}, 1000);
}
bannerFunc();
Use the getTimeZoneOffset for your date calculations. Then define all your dates as UTC dates. (https://www.w3schools.com/jsref/jsref_gettimezoneoffset.asp).
More about JS Dates

how to compare a user entered date to the current date and change a fields background color?

I am new to javascript and am working on a fallible PDF form and trying to set it to do multiple things. The first is I need to compare a user entered date to the current date to see if it is withing 5 years to the day. The second thing I need it to do is to change a fields background color if that date is at the 5 year time or outside of that range. This is the code I have been trying but it hasn't worked so far. There are 37 fields that need to be checked by this.
for(i=1;i<38;i++){
var Y = d.getFullYear();
var d = new Date();
var M = d.getMonth();
var d = new Date();
var D = d.getDay(); //n =2
var strDate = this.getField("Text"+[i]).value;
var arrDate = strDate.split('/');
var month = arrDate[0];
var day = arrDate[1];
var year = arrDate[2];
if(year+5>=Y){
if(M<=month){
if(D<=day){
this.getField("Text[i]").fillColor=color.red;
}}}}
I have updated this, it working now, can you try this now ?
for(i=1;i<38;i++)
{
var todayDate = new Date();
var strDate = "12/25/2009";
var arrDate = strDate.split('/');
var month = arrDate[0];
var day = arrDate[1];
var year = parseInt(arrDate[2]) + 5;
var userEnteredDate = new Date(year, month, day);
if(userEnteredDate <= todayDate)
{
//Color change code here...
}
}
The simplest approach so far as I know, is to instantiate a Date that is five years ago based on current time:
var t = new Date()
t.setFullYear(t.getFullYear() - 5) // t is five years ago
Then you just need to substract the user input date with this one, and see if the result is positive or negative:
var ut = new Date("......") // the Date instance from user input
if(ut - t >= 0) {
// within 5 years
} else {
// more than 5 years ago
}
The reason you can do so, is because when you substract two Date instances one another, they will be internally converted to timestamps. The less a timestamp is, the earlier the time is. So the result of substraction (a number) represents the time in between, in milliseconds.
If you don't care how long in between, you could just compare them:
var ut = new Date("......") // the Date instance from user input
if(ut >= t) {
// within 5 years
} else {
// more than 5 years ago
}
Try this
var d = new Date(),
Y = d.getFullYear(),
M = d.getMonth() + 1, // since this returns 0 - 11
D = d.getDay() + 1, // since this returns 0 - 30
strDate,
arrDate,
month,
day,
year;
for(var i = 1; i < 38; i++) {
strDate = this.getField("Text" + i).value;
arrDate = strDate.split('/');
month = parseInt(arrDate[0], 10);
day = parseInt(arrDate[1], 10);
year = parseInt(arrDate[2], 10);
if (((Y + 5) * 12 + M < year * 12 + month) || ((Y + 5) * 12 + M === year * 12 + month && D < day)) {
this.getField("Text" + i).fillColor = color.red;
}
}

Calculating timespan in years, months and days in JavaScript

I want to calculate the timespan between two dates (note: input format is dd.MM.yyyy, see code below). Special thing is, that don't want to use 30 days for every month and 360 days for a year. I rather want the difference in "human format" (don't know how to call it).
Let's say, I want to calculate difference (including the last day) from October 1 (2014) until March 17, 2015. From October to February this would make 5 months. And then the rest would be 18 days (from day 1 to 17, including 17th day). So the result should be :
0 years, 5 months, 18 days
This sort of calculation of course ignores that some months have 31, 30, 28 or 29 days (except for the day calculation, when dates are in such a form: start date: October 17th, 2014; end date: Januar 12th, 2015).
Unfortunately I didn't found any JS lib that already implements this sort of calculation. Moments.js, doesn't seem to have any methods for this.
So I started creating my own code but I'm still always off some days (2-3 days) from the expected result. And to be honest, if I look at my code I have the feeling that it sucks and there must be a more intelligent and elegant way to calculate this (in my example I'm outputting it to a span):
function getTimeDifferenceContract(startDateStr, endDateStr) {
var returnObject = { "years": null, "months": null, "days": null };
var startDateArray = startDateStr.split('.');
var endDateArray = endDateStr.split('.');
var startMonthIx = startDateArray[1]-1;
var endMonthIx = endDateArray[1]-1;
var startDate = new Date(startDateArray[2], startMonthIx, startDateArray[0]);
var endDate = new Date(endDateArray[2], endMonthIx, endDateArray[0]);
var endDateFixed = new Date(endDate.getTime()+(1*24*60*60*1000));
if (endDate > startDate) {
var years = 0;
var months = 0;
var days = 0;
var dateDiff = endDateFixed.getTime() - startDate.getTime();
var sD = startDate.getDate();
var sM = startDate.getMonth()+1;
var sY = startDate.getFullYear();
var eD = endDateFixed.getDate();
var eM = endDateFixed.getMonth()+1;
var eY = endDateFixed.getFullYear();
if (sY == eY && sM == eM) {
days = Math.floor(dateDiff / (1000 * 60 * 60 * 24));
}
else if (sY == eY) {
if (sD > eD) {
months = eM - sM - 1;
var startMonthRestDays = getMonthdays(sM, sY) - sD;
days = startMonthRestDays + eD;
}
else {
months = eM - sM;
days = eD - sD;
}
}
else {
years = eY - sY - 1;
var monthForYears = 0;
if (years > 0) {
monthForYears = (years - 1) * 12;
} else {
monthForYears = years * 12;
}
months = (12 - sM) + (eM - 1) + (monthForYears)
var startMonthRestDays = getMonthdays(sM, sY) - sD;
days = startMonthRestDays + eD - 0;
}
var lastMonth = eM - 1;
var yearForEndMonthDays = eY;
if (lastMonth < 1) {
lastMonth = 12;
yearForEndMonthDays = eY - 1;
}
var endMonthDays = getMonthdays(lastMonth, yearForEndMonthDays);
if (days >= endMonthDays) {
months = months + 1;
days = days - endMonthDays - 1;
}
if (months >= 12) {
years = years + 1;
months = months - 12;
}
returnObject.years = years;
returnObject.months = months;
returnObject.days = days;
}
return returnObject;
}
function main() {
var difference = getTimeDifferenceContract("30.09.2014", "01.10.2015");
var years = difference.years;
var months = difference.months;
var days = difference.days;
jQuery('#myText').text(years + " years, " + months + " months, " + days + " days");
}
main();
Fiddle: http://jsfiddle.net/4ddL27gx/2/
Any ideas to solve this?
I hope this will help:
Obtain difference between two dates in years, months, days in JavaScript
i was having the same necessity but no answer so i wrote a functions that seems to work...
i have used moment to achieve the result you need
var moment1 = new moment(new Date("30/Sep/2014"));
var moment2 = new moment(new Date("01/Oct/2015"));
var diffInMilliSeconds = moment2.diff(moment1);
var duration = moment.duration(diffInMilliSeconds);
var years = duration.years();
var months = duration.months();
var days = duration.days();
$('.div1').text(moment1.format());
$('.div2').text(moment2.format());
$('.div3').text(years + " years, " + months + " months, " + days + " days");
jsfiddle http://jsfiddle.net/mfarouk/qLqm3uuh/1/

Find year month day hour minute using time stamp

I'm using a mysql timestamp to calculate the difference of time through JavaScript as below,
function parseMySQLTimestamp(timestamp) {
var parts = timestamp.match(/^(\d{4})-(\d{2})-(\d{2}) (\d{2}):(\d{2}):(\d{2})$/);
return new Date(+parts[1], (+parts[2] - 1), +parts[3], +parts[4], +parts[5], +parts[6]);
}
var informTime = "2011-11-09 08:00:00";
var diff = (new Date()- parseMySQLTimestamp(informTime));
var months = Math.floor(diff /(60*60*24*30*1000));
diff=Math.abs(diff-(months*60*60*24*30*1000));
var days = Math.floor(diff/(60 * 60 * 24*1000));
diff=Math.abs(diff-(days*60*60*24*1000));
var hour=Math.floor(diff/(60*60*1000));
diff=Math.abs(diff-(hour*60*60*1000));
var minute=Math.floor(diff/(60*1000));
var message=months +" months "+ days + " D " + hour + " Hr " + minute + "min ago ";
alert(message);
it will give the correct result but I'm afraid that it will not be correct in the months which have 31,28 or 29 days other wise in leap years.
How to achieve reliable functionality? I feel it's so complicated. Thank you.

How to properly calculate remaining time in JS using getTime() from the two dates?

I'm trying to calculate remaining time (ex: 10 years, 2 months and 10 days from today(2014/03/02) in JS using this function:
var d2 = new Date(2024, 3, 12);
var d1 = new Date();
var d0 = new Date(1970, 0, 1);
var diff = new Date(d2.getTime() - (d1.getTime() + d0.getTime() ) );
var years = diff.getFullYear();
var months = diff.getMonth();
var days = diff.getDay();
alert("remaining time = " + years + " years, " + months + " months, " + days + " days.");
But instead of get the 10 years difference, I got 1980 years difference (though the days difference I understand that are produced buy the variation of days in months and years):
Is it possible to perform this "remaining time" operation using this strategy? If so, how to get the expected result?
Here the function in a JS shell: jsfiddle.net/3ra6c/
I find here the solution I was looking for:
var date1 = new Date();
var date2 = new Date(2015, 2, 2);
var diff = new Date(date2.getTime() - date1.getTime());
var years = diff.getUTCFullYear() - 1970; // Gives difference as year
var months = diff.getUTCMonth(); // Gives month count of difference
var days = diff.getUTCDate()-1; // Gives day count of difference
alert("remaining time = " + years + " years, " + months + " months, " + days + " days.");
And it seems to work very well!
As I explained, Date is not equipped with such functions and you have to do the math yourself. You can get the milliseconds difference between two dates, but then it's down to doing the math to represent that as you wish.
An example of using moment.js, loaded with require.js, with humanized approximations.
Javascript
require.config({
paths: {
moment: 'http://momentjs.com/downloads/moment.min'
}
});
require(['moment'], function (moment) {
var x = moment(new Date(2024, 3, 12)).from(new Date());
console.log(x);
});
Output
in 10 years
On jsFiddle
Look at their docs to see how you can humanize the output, you may want a little more detail.
var diff = new Date(d2.getTime() - (d1.getTime() + d0.getTime() ) )
Why do you add d0? Try to remove it.

Categories

Resources