Get difference In minute of two dates - javascript

I Want to get difference in minutes of two dates, Meaning-
var diff= Current_Date- Date_Abc
and diff should in minutes.
What I want to do.
I have a GPS device And its get reporting every 30 second. If this device stop reporting from 90 minutes than I want to get stop flag for this.
In reporting information there is date Time "2017-06-21 12:55:21" in this format.
So I want to check If(CurrentDate-ReportedDateTime>=90) then DeviceStoped= true else DeviceStoped=false.
How do this in ext JS or in Java script

If your dates are timestamps or instances of Date, you can try the following:
const ONE_MINUTE_IN_MILLISECONDS = 1000 * 60,
diff = (currentDate - pastDate) / ONE_MINUTE_IN_MILLISECONDS;
So it's very straightforward, you can easily calculate the difference in milliseconds, then you just need to convert it to minutes.

Get the milliseconds of both the dates and compare the difference with 90 minutes (5,400,000 ms).
var diffMs = (Date_Abc- Current_Date); // milliseconds between Date_Abc &
Current_Date
var diffMins = Math.round(((diffMs % 86400000) % 3600000) / 60000); // minutes
To discard the seconds.
diffMins = Math.floor(diffMins)

Related

Convert getFullYear() in seconds in Javascript

Are there any way to convert the GetFullYear() in real time seconds from the beginning of the current year? Instead of having a output of 2017, i have a dynamic seconds until the end of the year.
As well as obtaining the maximum value of the GetFullYear() converted in seconds to make some calculations.
Thanks in advance
var date1 = new Date("1/1/2017");
var date2 = new Date("2/2/2017");
var timeDiff = Math.abs(date2.getTime() - date1.getTime());
var diffDays = Math.ceil(timeDiff / (1000 * 3600 * 24));//returns 32
var time_in_seconds = diffDays*60*60;// calculate the date in seconds.
Are there any way to convert the GetFullYear() in real time seconds from the beginning of the current year?
To get the difference in milliseconds between two dates, just subtract them. To get ms from the start of the year, subtract now from a date for 1 Jan at 00:00:00, e.g.
function msSinceStartOfYear() {
var now = new Date()
return now - new Date(now.getFullYear(), 0);
}
console.log(msSinceStartOfYear());
As well as obtaining the maximum value of the GetFullYear() converted in seconds to make some calculations.
According to ECMA-262, the maximum time value is 9,007,199,254,740,992, which is approximately 285,616 years after the epoch of 1 Jan 1970, or the year 287,586. So that is the theoretical maximum value of getFullYear.
However:
new Date(9007199254740992)
returns null. The actual range is exactly 100,000,000 days, so to get the maximum value, multiply days by the number of milliseconds per day:
new Date(100000000 * 8.64e7).getUTCFullYear() // 275,760
converted to seconds:
new Date(Date.UTC(275760, 0)) / 1000 // 8,639,977,881,600 seconds
but I have no idea why you want to do that. I've used UTC to remove timezone differences. Using "local" timezone changes the values by the timezone offset.

Getting a MySQL DateTime in PHP to seconds in javascript

I have a countdown timer in javascript. It has two variables. Both store current dates. One variable (currentDate) is converted to milliseconds and then milliseconds according to 10 minutes is added. Other variable (d) stores current datetime in a function that is run every second. That function takes difference between these two and displays in seconds. That works. Below is the code.
<script>
var currentDate = new Date();
var d =new Date();
var tl = currentDate.setTime(currentDate.getTime() + 2*60*1000);
var seconds =(tl - d)/1000;
function secondPassed() {
var minutes = Math.round((seconds - 30)/60);
var remainingSeconds = seconds % 60;
if (remainingSeconds < 10) {
remainingSeconds = "0" + remainingSeconds;
}
document.getElementById('countdown').innerHTML = minutes + ":" + remainingSeconds;
if (seconds == 0) {
clearInterval(countdownTimer);
document.getElementById('bonus').innerHTML = "Buzz Buzz";
} else {
seconds--;
}
}
var countdownTimer = setInterval('secondPassed()', 1000);
</script>
But problem is that every time I refresh the page, the countdown starts again from 10 minutes. I want to store a particular datetime (TIMESTAMP) in php (which will be stored when user visits the page). Then I will add 10 minutes to that and that datetime will be taken as reference in javascript to subtract current timestamp from.
So basically I need to convert php datetime (TIME_STAMP) to milliseconds, give that to javascript, add milliseconds according to 10 minutes to it, and subtract milliseconds corresponding to current datetime to get remaining time in the function.
The gettime method in javascript uses 1970-01-01 00:00:00 as refernce to convert into milliseconds. So, in short I need to get milliseconds between that and the stored datetime(TIMESTAMP). How can I do it?
I need to do this in php, not MySQL, so this question : MYSQL - datetime to seconds does not help me.
EDIT : I am storing date as TIMESTAMP in MySQL.
Use PHP's time function to get seconds since the epoch:
Returns the current time measured in the number of seconds since the Unix Epoch (January 1 1970 00:00:00 GMT).
http://us3.php.net/time
It's not completely clear to me from your question how you're storing the time stamp in the DB, but if it's a MySQL DATETIME, when you select it from the DB use SELECT UNIX_TIMESTAMP(time_col) to convert it to seconds since the epoch on the fly. Now you're dealing with UNIX timestamps in all cases.
UNIX_TIMESTAMP docs here

Jquery Countdown To Next Wednesday 11pm

I need to write a function that will take a javascript date object in UTC time. It needs to find the difference in seconds from the given date and next (or coming) Wednesday 11pm then put it in a countdown object. Once the the timer hits 0, I need it to restart again. I know I have to use the getDay() function somehow but I'm unsure of how to go about this.
Logic and Code
You don't need jQuery for the countdown timer itself. The date object is part of plain vanilla JavaScript.
For UTC, you'll want to use the getUTCDay() method.
Assuming givenDate is a Date object, the following would calculate how many days until the coming Wednesday (day 3).
var daysUntilTarget = (3 - givenDate.getUTCDay() + 7) % 7;
If given date is on a Wednesday, the above will return 0 and you'll need to determine if target time has passed yet. You could use something like this:
var daysUntilTarget,
targetDay = 3,
targetHour = 23,
targetMinute = 0,
targetSecond = 0;
if (
targetDay == givenDate.getUTCDay() &&
targetHour * 3600 +
targetMinute * 60 +
targetSecond * 1 <
givenDate.getUTCHours() * 3600 +
givenDate.getUTCMinutes() * 60 +
givenDate.getUTCSeconds() * 1 +
givenDate.getUTCMilliseconds() / 1000
) {
//given date is after target time on target day
daysUntilTarget = 7;
}
Use the setUTCDate() and setUTCHours methods to set the target date and time.
var targetDate = new Date(givenDate);
targetDate.setUTCDate(givenDate.getUTCDate() + daysUntilTarget);
targetDate.setUTCHours(targetHour, targetMinute, targetSecond);
Use the getTime() method to get a timestamp for both the given date and the target date. Then you can calculate the difference between these and divide by 1000 to get the number of seconds.
var countdownSeconds = (targetDate.getTime() - givenDate.getTime()) / 1000;
The following will convert the total seconds into days, minutes, and seconds. You can then write these to an element in your HTML.
var daysLeft, hoursLeft, minutesLeft, secondsLeft;
secondsLeft = parseInt(countdownSeconds);
daysLeft = parseInt(secondsLeft / 86400);
secondsLeft = secondsLeft % 86400;
hoursLeft = parseInt(secondsLeft / 3600);
secondsLeft = secondsLeft % 3600;
minutesLeft = parseInt(secondsLeft / 60);
secondsLeft = parseInt(secondsLeft % 60);
Be sure to convert countdownSeconds to an integer before doing further calculations with it. Otherwise, you may get undesired results due to floating point math. For example,
0.009 / 86400 = 1.0416666666666665e-7;
parseInt(1.0416666666666665e-7) = 1;
parseInt(0.009 / 86400) = 1; //probably not what you were expecting
Countdown Timer
To update the timer, you could decrement a counter or use the client machine's clock to keep time.
The counter method is not as accurate as the clock method because the former doesn't take into account the amount of time it takes for the code to run. I've noticed a 3-second loss over a half-hour period. Adjusting the loop interval will not fix this since different browsers run code at different speeds. And code may run slower for other reasons such as when machine is low on memory.
The client machine's time may not be accurate to begin with. However, the server time can be compared to the client time initially to calculate an offset. Then the client time can be used as a counter rather than an absolute value. The draw back is that if the client time changes, it will affect the countdown. Note that time zone changes and changes due to Daylight Saving Time will not affect the countdown since they do not affect the timestamp.
Examples
I've created two fiddles using the code described above.
Countdown Timer (Using Counter)
Countdown Timer (Using Clock)

Increment a var by one every 24 hours from a specific date

I've never used Javascript before (or any other programming language) so sorry for asking this question because im sure it's very simple.
What I want to do is set a date in Javascript, then increment it by one every 24 hours. So three days after the date is set, 3 is displayed in the HTML (not the date itself). And after 100 days, 100 is displayed.
Thank you.
You have to create two date objects, one representing your initial date, and another one representing right now. Then, calculate the difference:
// Calculate days since Dec 1st 2012
var initialDate = new Date(2012, 11, 1); // Attention: month is zero-based
var now = Date.now();
var difference = now - initialDate;
var millisecondsPerDay = 24 * 60 * 60 * 1000;
var daysSince = Math.floor(difference / millisecondsPerDay);
alert(daysSince); // 80
http://jsfiddle.net/PmYFc/
If you are looking to show how many days the page has been open, you want to use the setInterval function: https://developer.mozilla.org/en-US/docs/DOM/window.setInterval.
So, if your HTML element looked like <span id='example'>0</span>, your JS might look like this:
var date = 0,
element = document.getElementById("example");
setInterval(function(){
date++;
element.innerText = date;
}, 1000 * 60 * 60 * 24); //milliseconds, seconds, minutes, hours
Though, it seems unlikely any page would sit unrefreshed for any significant length of time. If you need to persist the date variable beyond page refreshes you could look into localstorage.

Calculate amount of time until the next hour

I'm working on a busing website project and the buses run every hour. I'm having trouble creating a widget that finds the time between now and the next hour, so that it is clear when the next bus will run. My client requires that it is in javascript. Any suggestions?
Thanks in advance.
To know exactly the miliseconds from now to the next hour:
function msToNextHour() {
return 3600000 - new Date().getTime() % 3600000;
}
Please note that this will strictly tell you how many milliseconds until the NEXT hour (if you run this at 4:00:00.000 it will give you exactly one hour).
function getMinutesUntilNextHour() { return 60 - new Date().getMinutes(); }
Note that people who's system clocks are off will miss their bus. It might be better to use the server time instead of the time on the client's computer (AKA at least partly a non-client-side-javascript solution).
you have the Date object in Javascript, you could do something like:
var now = new Date();
var mins = now.getMinutes();
var secs = now.getSeconds();
var response = "it will be " + (60 - mins - 1) + " minutes and " + (60 - secs) + " seconds until the next bus";
of course you will have to work more on those calculations, but that's how you work with time in javascript
Either of the other two answers will work well, but are you aware of the docs available to you about all the other nice things date is JS can do for you?
Mozilla Date Docs
https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Date
Lots of answers, a really simple function to get the rounded minutes remaining to the next hour is:
function minsToHour() {
return 60 - Math.round(new Date() % 3.6e6 / 6e4);
}

Categories

Resources