How to compare datetime in javascript - javascript

I have been trying to get the code to work for more then 2 hours, then I tried this site, well there is alot of code here! I have used each of them. Some are in jQuery while some were pure JavaScript.
Here is two of the code that I have tried:
First code: This code was caught from this link: https://stackoverflow.com/a/2725097/1762944
var dateTimeStr = "17:10:03";
var user_time = DateTime.Parse( dateTimeStr );
var time_now = DateTime.Now;
if( time_now > user_time )
{
// your code...
}
Second code: This one is jQuery. It worked for the asker, and was marked as answer too. It works I have checked the fiddle provided by him! But when I tried the code, it didn't work either. Here:
function time_until() {
currentTime = Math.floor(jQuery.now() / 1000);
seconds = eventTime - currentTime;
if(second == 0){
//Stop voting
}
days = Math.floor(seconds / (60 * 60 * 24));
$('#time').html('seconds ' + seconds + '<br/>days ' + days);
}
I have tried to edit them both. But they don't work.
Reason why they work: The reason behind this all, is that what I want to do is,
I have a database table which is storing the time for users. I mean when they made an activity such like posting status updates!
I have created a timestamp. Which shows perfectly like this: few seconds ago.
Now what I want is, to update the time to 1 minute ago without reloading the page, like Facebook does. Or whatever the time is, to get updated to the next minute or hour or corresponding.
What I have tried is almost next to everything. But I guess the only issue with my codes is that when I place the DateTime.Now value from Database in it, it shows an error. The error is hidden so I have created an else statement like this:
if(seconds < 60) {
$("#jstime").html(seconds + "seconds..");
// else if minutes, if hours they are all written..and then an else
} else {
$("#jstime").html("Again an error, try again bud");
}
I have a setInterval which keeps on updating the id with the error text.
Here is the code that I am using.
<span id="timeval" title="#timeStamp">#TimeStamp</span></div>
<input type="hidden" id="time" value="9/23/2013 8:10:40 PM" />
<span>Real time: #TimeStamp</span><br>
<span id="update">Updated time: no update till now;</span><br>
<span id="jstime">Time</span>
The timeval is the real time that is being shown to the users, input is the time from where I get the value of the time on each post, the next span just shows the time to me, I mean I used this to check what was the time when the page was loaded, update is the span to show the updated time, jstime can also be used to show the updated time.

The problem is that you stored currentTime in the function you call every n seconds. As it gets looped it will everytime create a new current time.
Make it a global variable so you can loop through the function without creating the time new and use the old time instead.

Please go to link on stackoverflow and see my answer on how can we compare two dates along with the time in Javascript.

Related

synchronising the Time without reloading the page

I'm building a web app that uses the Time of the computer I found how I can get the hours and the minutes and I succeeded to update them to the UI but the minute field is not synchronised with the time of the computer I have to reload the page to see it updated with the new value, I don't know how to solve this problem I feel like it's a stupid question but really I'm struggling with it, it's my first app with JavaScript so forgive me :p
I tried the setInterval but it didn't work too any help please
here is my code:
HTML
<div class="headTime" >Time: <span class="Time"> 03:19</span></div>
Js
var hours=d.getHours();
var minutes=d.getMinutes();
var Time=" 03:19";
var newTime=Time.replace("03",hours);
var newTime=newTime.replace("19",minutes);
setInterval(function(){
document.querySelector(".Time").innerHTML=newTime;
},1000);
any better title for the question?
I feel it's not accurate
You need to get the date each time in callback passed to setInterval. I have added seconds also for test purpose.
You donot need to get the test of span and use replace() and then show. You could directly use Template Strings
`${hours}:${minutes}`
Tip for you is declare the element .Time in global scope and don't call querySelector every second
const span = document.querySelector(".Time");
setInterval(function(){
let date = new Date();
let hours = date.getHours();
let mins = date.getMinutes();
let seconds = date.getSeconds();
span.innerHTML= `${hours}:${mins}:${seconds}`;
},1000);
<div class="headTime" >Time: <span class="Time"> 03:19</span></div>
Note:If you are only showing the minutes no seconds you shouldn't call the function every second

How to check H2 tag with a date against 1 week in the future on a simple web page

Let's say I have the following HTML page;
<html>
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.18.1/moment.min.js"></script>
</head>
<body>
<h2 id='invoiceDueDate'>17/08/2018</h2>
<h2 id='paymentStatus'>Yet To pay</h2>
</body>
</html>
I need to check the h2 for the due date, check the payment status for whever its paid or not and if the current day is one week past the invoiceDueDate and is still unpaid then the page needs to display Payment Over Due
It may be obvious but if it is paid then do nothing.
It doesn't necessarily have to use moment.js but it has to use this date format: dd/mm/yyyy
Here is the javascript I have used to try to get it working:
let dueDate = document.getElementById('invoiceDueDate').innerHTML;
console.log(dueDate)
// this get the the due date from the html and I have used console.log to confirm it works
let invoiceStatus = document.getElementById('paymentStatus').innerHTML;
console.log(invoiceStatus)
// this get the theinvoiceStatus from the html and it works
const overDue = moment().add(7, 'days').format('L');
console.log(overDue)
// get the current date and adds 7 days and it works
// todays date isnt the due date so adding 7 on to it doesn't work
if(invoiceStatus.innerHTML === 'Yet To pay'){
if(dueDate >= overDue){
invoiceStatus.innerHTML = "Overdue";
console.log('overdue');
}else{
invoiceStatus.innerHTML = "Un-paid";
console.log('not yet paid');
}
} else {
// do nothing
}
// compares the dueDate to overDue then print it out to the page
The problem with this javascript is it checks the current date then adds 7 days then print the result rather than adding 7 days to the due day THEN printing the result. This is the problem I'm struggling with.
I hope this makes sense.
Edit:
Also is there anyway to do soemthing like this
if(dueDate >= (dueDate + 7 days)){
invoiceStatus.innerHTML = "Overdue";
}
I've made changes and added it to codepen:
https://codepen.io/anon/pen/rZaLvb?editors=1010
It appears that your logic is requiring these to be completely identical. You might want to check instead to see if overdue >= dueDate -- otherwise, it will only count things that are precisely overdue, and not n days overdue.
Also, at some points you're trying to hit the innerHTML of an item's innerHTML.
The changes I would make here:
1) Change:
let invoiceStatus = document.getElementById('paymentStatus').innerHTML;
console.log(invoiceStatus);
To:
let invoiceStatus = document.getElementById('paymentStatus');
console.log(invoiceStatus.innerHTML);
2) Change:
if(dueDate === overDue){
To:
if(overDue >= dueDate){

Advice on this script

I have no knowledge of any sort of coding/ computer languages and need help using this script for a flash sale.
setInterval(function() {
var m = Math.floor((new Date).getTime()/1000);
if(m == '1476693000000') {
document.getElementsByTagName('a')[43].click();
}
else {
console.log("Script Activated…");
}
},10);
My question is what does this script 'really' do and is there any way to further improve it to enhance chances of buying the desired product?
This script has been described to be used for a flash sale on Mi India website and has been sourced from
http://trickweek.com/mi-rs-1-flash-sale-script-trick-buy-successfully-redmi-note3-mi4-rs-1/
It appears, that your script waits for a described time (2PM today) and once your system's time is 2PM it clicks on a specific link.
In this code, this line is
var m=Math.floor((new Date).getTime()/1000);
is unnecessary, erroneous and should be replaced by
var m=(new Date).getTime();
since it is later comparing m with an actual millisecond value.
Also, setInterval
It takes two parameters - callback handler and millisecond value.
It invokes the callback handler every 10 milliseconds.
The setInterval executes what is inside the function body every 10 milliseconds.
Var m gets the largest integer less than or equal to what is inside parenthesis.
Then goes the if condition to check if m equals 1476693000000 then the 43rd (starting from 0) element (tag) a gets found and clicked. If the if condition fails the else condition gets executed which prints to console log Script Activated….
The logic is simple. He is checking the flash sale time for every 10 milliseconds. Once the time reached, he is getting the "Add to cart" button on the page and clicking it dynamically.
I will explain you clearly.
For Example:
Mi mobiles flash sale is going to start on 17th October, 2016 at 2pm exactly. So, through javascript, he is checking the current time reached the expected time or not.
Usually, we cannot compare directly date with another date. So, we need to convert the date with time into most accurate time i.e, into milliseconds. so we can get the flash sale date's timestamp(time in milliseconds)..
var flashSaleTime = new Date("2016/10/17 02:00:00:000 PM").getTime();
Note: In Javascript, Default date format is YYYY/MM/DD and getTime() methods returns date in milliseconds.
So, We need to check the current time(in milliseconds) reached falshSaleTime, We need to click the Add To Cart button dynamically.
var flashSaleTime = new Date("2016/10/17 02:00:00:000 PM").getTime();
setInterval(function(){
var currentTime = Math.floor((new Date).getTime()/1000);
if(currentTime*1000 === flashSaleTime){
document.getElementsByTagName('a')[43].click();
}
},10);
here, setInterval function check the condition for every 10 milliseconds.
So, once current time reaches the target time, we are getting reference to the button and triggering click on the button.

How do I update time on multiple rows using javascript

I'm using the fromNow function from moment.js library to display time elapsed from a specific date/time (e.g. '16 hours ago'). I use this within a table on multiple rows within my web app.
This part works fine, but I need the time to count continuously and for several rows (50 - 60 and growing). How do I get the time to count continuously and efficiently? I say efficiently because, I've read that using interval may be a bad idea so I'm not sure and I need help understanding.
This is how I create a cell which holds the elapsed time:
newCell = row.insertCell(++cellIndex);
newText = document.createTextNode(moment(data.checkintime).fromNow());
newCell.appendChild(newText);
Assuming the code you posted is correct, you can save the updated time in a variable and update all the rows. In that way, it's the same time that will display for all the rows and that time would just have to be done in one time:
var updatedTime = moment(data.checkintime).fromNow();
newCell = row.insertCell(++cellIndex);
newText = document.createTextNode(updatedTime);
newCell.appendChild(newText);
If you want the timestamp to continuously update, look into a library such as TimeAgo.
With your current code, simply change the text node to match timaeago's syntax <abbr title='{timestamp}' class='timeago'> and add the following javascript to the bottom of your page
jQuery(document).ready(function() {
jQuery("abbr.timeago").timeago();
});
This will continuously update the timestamp ("a moment ago", "2 minutes ago"....) which I believe is what you're looking for

working with filenames and scheduled function calls in javascript

I have a couple questions about javascript:
Does javascript have the capability to identify a filename with a timestamp as a name?
Similar to the Perl code below utilizing the POSIX module?
my $filepath = sprintf("/path/to/file%s.JSON",strftime("%y%m%d",localtime));
this is just an example. I would like to find file in format yy/mm/dd/hh/min
For example say I want to find a file with the name 12_11_03_15:15.json how can I do this with javascript.
Say I create a function that I want to trigger every 15 minutes to read the file how is this possible with javascript? I looked at setInterval() but that won't work because it is dependent on when the browser is launched. Is it possible to schedule a function to execute every hh:00, hh:15, hh:30, hh:45?
Thank you very much in advance.
You can use the Date class to get information about the current time.
To schedule a function to run at a certain time, setInterval() is indeed the best choice. It seems like what you're really looking for is a way to find out when to start the first interval such that it will fall on a quarter-hour. For that, you should again use Date to get the current time and subtract it from the next quarter-hour; you can use the resulting value with setTimeout to time the start of the first interval.
Here's an example: http://jsfiddle.net/GSF6C/3/
var nextQuarterHour = new Date();
nextQuarterHour.setMilliseconds(0);
nextQuarterHour.setSeconds(0);
do {
nextQuarterHour.setMinutes(nextQuarterHour.getMinutes() + 1);
} while (nextQuarterHour.getMinutes() % 15)
var millisecondsToNextQuarterHour = nextQuarterHour.getTime() - Date.now();
document.write(millisecondsToNextQuarterHour);
setTimeout(function () {
alert("Ding!");
setInterval(function () { alert("Dong!"); }, 15 * 60 * 1000);
}, millisecondsToNextQuarterHour);
​
​

Categories

Resources