How to get correct timestamp value in nodejs? - javascript

In my project my scheduling to post in social network sites using cron job,
timestamp value should end with zero instead of 1.
here is the node js code used:
var rule = new cron.RecurrenceRule();
rule.second = 0;
cron.scheduleJob(rule, function(){
var now = new Date();
var date = dateFormat(now, "dd-mm-yyyy, h:MM:ss TT");
console.log(Math.floor(new Date()/ 1000));
retrivepost(Math.floor(new Date()/ 1000).toString());
});
here is the timestamp value output log which i get in terminal
1517894101
1517894161
1517894221
1517894281
1517894341
1517894401
1517894461
1517894521
1517894581
1517894641
1517894701
1517894761
1517894821
1517894881
1517894941
1517895001
1517895061
1517895121

For me your code works just fine and logs timestamps ending with the zero second just like scheduled.
However, I think if your retrievepost() function depends on a timestamp being on the minute exactly you should round your date inside the .scheduleJob function to the nearest minute. A whole second later seems odd to me but imagine that you have some code just above that takes a while to compute. retrievepost() will fail then, even if you get it working right now.

Related

How to get local time date instead UTC time in Node.js?

I want to get variable to save image name format using the date.
I use this following code.
const time = new Date().toJSON().slice(0,10).replace(/-/g, '');
My expected variable is 20220629. Because my local time is June 29, 2022.
But, the result variable is 20220628. I think this result time using UTC time.
Update:
I try to using JS method like toLocalDateString() and get local time.
const time = new Date().toLocaleDateString().replaceAll('/', '');
But the result is 29062022 not 20220629.
Can anyone help me how to convert into localtime? Thank you.
The date functions rely a lot on system settings to get your local date and time. If you're in the U.S. that happens to be month/day/year.
You simply need to deconstruct it to get what you're looking for. The below code will get it in the order you're looking for (and account for the month being 0-indexed):
const time = new Date()
const time2 = '' + time.getFullYear() + (time.getMonth() + 1) + time.getDate().toString().padStart(2,'0')
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date

How to add input from a prompt to the local time using only JavaScript?

I'm a software engineering student in an Intro to JavaScript course and I'm stuck on an assignment. Here's the assignment,
in a file named alarmTime.html, use prompt() to find out how long the user wishes to nap. Then, write a statement to the document telling the user what time her/his alarm should go off. Be sure the times are local for the user.
I'm stuck on adding the input to the user's local time. I don't really know what I'm doing wrong and I'm having difficulty understanding what to do because all I'm getting is what seems to be random numbers. Please take a look at my code and point me in the right direction.
var howLong = prompt("How long, in hours, do you want to nap for?", 1);
var parsedInput = parseFloat(howLong);
var today = new Date();
var currentTime = today.toLocaleTimeString();
var myHour = today.getHours(currentTime);
var alarm = today.setHours(myHour + parsedInput);
document.write(alarm);
The reason is because of this statement document.write(alarm);. setHours method in Date object updates the Date instance, and returns the Date in milliseconds. Therefore, you are printing the Date object as the number of milliseconds since January 1, 1970. To fix that, simply replace it with document.write(today);
The problem is var alarm = today.setHours(myHour + parsedInput);
instead try to set the variable as
var alarm = today.getHours();
or change document.write(alarm); to document.write(today);
Date.now() will give you current time (users local time). Add time from prompt and your good:
let napTime = prompt('how many minutes do you want to nap?');
let alarmTime = new Date(Date.now()+napTime*60000);
//if you want to get HOURS instead of minutes
//let alarmTime = new Date(Date.now()+napTime*3600000);
//print it out. toLocale...() functions return local FORMAT of the datetime,
//they dont deal with timezones
document.write('set alarm to '+alarmTime.toLocaleTimeString('en-US'));
console.log(alarmTime);

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.

Compare Server Time and Browser Time

My table that has 3 columns: FileName, LastUpdateTime, and a Restart button.
I need to display the restart button only if the last update time is more than 20 min ago. I get the last update time from the server. d = new Date() gives the local browser time but the lastUpdateTime is coming from the server. Server is in the different time zone than the clients browser.
The following code works if both server and browser are in the same time zone. Do you have any suggestions on how solve this if the server and browser are in a different time zone?
This application supposed to run anywhere in US and Europe.
var lastUpdatedTime = (gridData[i].LastTimeUpdated);
var d = new Date();
//deducting 20 min from current time
var deductTwenty = d.setMinutes(d.getMinutes() - 20);
var parsedupdatetime = Date.parse(lastUpdatedTime);
// If the last update time is not 20 ago, hide it.
if (parsedupdatetime > deductTwenty) {
newrestartButton.hide();
}
Use .NET in your .cshtml file to get the date server-side. Assuming you use MVC (since you tagged this question kendo-asp.net-mvc).
#{
var deductTwenty = DateTime.Now.AddMinutes(-20);
}
<script>
var jsDeductTwenty = new Date(#deductTwenty.Year, #deductTwenty.Month-1, #deductTwenty.Day, #deductTwenty.Hour, #deductTwenty.Minute);
</script>
Result:
What's probably going wrong is the server date parsing. Take a look at the Date.parse function spec - and make sure your server is returning something that will get parsed correctly like an ISO8601 formatted date.
You have to convert your lastUpdatedTime with client timezone, means you should convert server time to client time when subtracting date with 20 mins. You can use momentjs, moment-timezone and jstimezonedetect to achieve this.
Your code should be like this
// get current client timezone with jstimezonedetect
var currentTz = jstz.determine().name(); // e.g "Europe/London"
// parse last update time to moment object and change its timezone
var lastUpdateTime = moment(lastUpdatedTime, "M/DD/YYYY hh:mm a").tz(currentTz);
// create date using moment and deduct 20 mins from it
var deductTwenty = moment().subtract(20, 'minutes');
// now compare
if (lastUpdateTime > deductTwenty) {
newrestartButton.hide();
}
Hope this help.

Javascript: Storing the current time's timestamp value

Is there a way to store the current timestamp in a Javascript variable? The reason is I want to compare Javascript's current time value with a Django time variable, and whenever the time matches, it will send a popup notification.
I guess reloading the page maybe every 3 seconds or so would work, but that seems extremely inefficient.
I'm not sure exactly what you're trying to do here. It's not likely the times will ever match exactly unless you check every millisecond, but you can always check when the time is greater than the django variable, or within a certain range. This will check the time every three seconds.
var django = // Create a javascript date object from django timestamp here
var interval = setInterval(function(){checkTime()}, 3000);
function checkTime() {
var d = new Date();
if (d >= django) {
//Do something here
clearInterval(interval);
}
}

Categories

Resources