I have a functie that keeps track of the local time live. I'm using the new Date(); object to get the local hours, minutes and seconds.
I also want the user to give a input where a function has to start on a specific time. The input of the user is a string (I don't want the user to work with the Date(); object as not all users can program). For example:
Input user:
var timeStart = "10:08:30";
Live time converted to string:
var sTime = todayHours + ':' + todayMinutes + ':' + todaySeconds;
When the two are equal:
if(sTime == timeStart )
{
//function when equals time
//This function has a timeout, so it will run infinite times
var timeOutId = setTimeout(function()
{
//call functie
}, 10000); //every 10 seconds as example
}
Alright this work just fine. I can compare strings only if they are the same or not. However to make it a little bit more complicated: I also want the user to give a end time, when to function has to stop:
Input user:
var timeEnd = "11:08:30";
Live time converted to string:
var sTime = todayHours + ':' + todayMinutes + ':' + todaySeconds;
When the two are equal:
if( sTime == timeEnd)
{
//function when equals time
//calls the timeout id and stops it
clearTimeout(timeOutId);
}
Now this just works fine! However now you know what i'm trying to do i'm wondering if i can do in some way:
if(sTime >= timeStart && sTime <= timeEnd)
{
//timeout will only be set when it's in between the given time
setTimeout(function()
{
//call functie
}, 10000); //every 10 seconds as example
}
Question
I there a way i can transform my string time(using 2-digits method) in a excisting date time so i can compare it on time?
My time only uses [hour, minutes and seconds], which causes problems as the Date(year, month and day) is not defined.
I've tryed to use Momentjs but it also refuses to work with only hour, minutes and seconds. Or i might not be farmilier on how to do this.
The method i want to use seems much easier as i don't have to define when to cancel the timeOut.
Any help is appreciated!
P.s What i actually just have to accomplish is converting the string time to a unix time stamp (Of course other methods are welcome too).
Dont know moment.js but you could still use basic parseInt to extract the time , turn it into and integer so you can compare it with another one :
function stringtime_to_seconds(aString){
var time,a = aString.split(":");
switch(a.length){
default: // 3 , you'll need to handle other cases
time = parseInt(a[0])*3600+parseInt(a[1])*60+parseInt(a[2]);
}
return time;
}
then you can compare dates.
I've tryed to use Momentjs but it also refuses to work with only hour, minutes and seconds. Or i might not be farmilier on how to do this.
...
What i actually just have to accomplish is converting the string time to a unix time stamp
You simply need to provide the format string, such as:
// parse the input
var timeStart = "10:08:30";
var m = moment(timeStart,"HH:mm:ss");
// then one of these
var s = m.unix(); // unix time in seconds
var ms = m.valueOf(); // unix time in milliseconds
Of course, to get unix time you have to have a specific date in mind. With the above method, it will use the local time zone's "today". This might be a concern if you have a range that spans over midnight, such as 10pm - 2am, so you might need to adjust.
Also, you said you were doing a range comparison like:
if(sTime >= timeStart && sTime <= timeEnd)
You probably should not do that with strings. But also, you should use a half-open interval [start,end). In other words:
if(sTime >= timeStart && sTime < timeEnd)
Usually when someone says 1:00 to 2:00, they mean that the range is over at 2:00.
Related
I want to pass the time variable extracted from the database as a Date function in jQuery and want to extract hours and minutes from it and want to store it in a javascript variable.
var time="<?php echo $row['time']; ?>";
var time=new Date(time);
var hrs=time.getHours();
var min=time.getMinutes();
Please find if there is any error in this code.
Without more knowledge I can't really give you an answer.
But its likely that you're expecting a Date Object, when in reality your DB is returning something else.
(Maybe a string?, a number?)
Make sure what type of data is exactly storen in your "time" variable. Would be my suggestion because I dont see errors in the code. Must be the logic
Really hope this helped but more insight into what your DB is doing would help getting a clear answer :)
Good Luck !
You could find answers for this all over Stackoverflow or read the docs on the date object.
However, here is an answer you might like
var myMinutes = 1; // This represent 1 minute subtraction
var myHours = 60; // This represent 60 minutes subtraction which is 1 hour
var dateMSubObject= new Date(oldDateObject.getTime() - myMinutes*60000); //Substracting your minutes variable
var dateHSubObject= new Date(oldDateObject.getTime() - myHours*60000); //Substracting your hours variable
To make it more managable you could do hours like this aswell for etc 24 hours
var myHours = 60*24; // This represent 24 hours subtraction
You could also make the above code a function which wil take paramters like units, type and from that return your desired result
The 60000 part is milliseconds and represents 1 minute.
And welcome to StackOverflow, if you take some time exploring the website you will quickly be able to find the most common questions usually followed by great answers :)
This did it for me:
let jsdate = new Date(unixtimestamp+1000);
example in use:
let a = new Date();
console.log("a ="+a)
let stamp = a.getTime()
console.log("stamp ="+stamp) // timestamp
let newTimeObj = new Date(stamp*1000)
console.log("newTimeObj :::::::"+newTimeObj)
OUTPUT::::
You need to convert the UNIX Timestamp(in seconds) which is coming from your PHP code to milliseconds, and then pass it as a parameter to a Date object.
Consider the below example in JavaScript:
//UNIX Timestamp from your PHP code
let timeInUNIXTimeStamp = "1581653281";
// Create a new JavaScript Date object based on the timestamp
// Multiplied by 1000 to convert it into milliseconds, from seconds, as Date object works in milliseconds
var date = new Date(timeInUNIXTimeStamp * 1000);
// Get Hours part from the timestamp
var hours = date.getHours();
// Get Minutes part from the timestamp
var minutes = "0" + date.getMinutes();
// Will display time in H:M format
var timeInHMSFormat = hours + ':' + minutes.substr(-2);
console.log(timeInHMSFormat);
You can same achieve in PHP also, there you need to convert UNIX Timestamp to H:M format, using the date() function, where the first parameter will the format you wanted and the second will be your UNIX Timestamp.
Example: date("h:i", 1581653281);
Where h is hours, in 12-hours format
i is minutes
Read move about PHP's data() function Date function in php
Consider PHP the code below, inside your JavaScript:
var time="<?php echo date('h:i', $row['time']); ?>";
//Now Split the above string into array
var timeArray = time.split(":");
var hours = timeArray[0];
var minutes = timeArray[1];
For more detail see this answer Convert UNIX Timestamp
I am trying to find time differences. Difference is NaN. What should I do?
currentTime.format() = 2016-12-07T11:43:19+03:00
pws.lastDataTime = 2016-12-07T08:35:14.4126931+00:00
var difference= currentTime.format() - pws.lastDataTime;
currentTime.format() = 2016-12-07T11:43:19+03:00
currentTime.format is a function. You can't assign it's return value to something.
currentTime.format() - pws.lastDataTime
I don't think the format function returns a number, but instead a string or an object. If you subtract anything from them, they return NaN (not a number). You need to either convert both to milliseconds and subtract one from the other, or calculate the year, month, day, hour, second and millisecond separately.
I don't know what denomination you want, so I'll just show you how to find it in milliseconds.
If already you have a date or two, you can use date.getTime().
var stackOverflowLaunchDate = new Date(2008, 8, 15);
var today = new Date();
var diff = today.getTime() - stackOverflowLaunchDate.getTime(); // milliseconds since Stack Overflow was launched
If you don't have (and don't need) a date object, use Date.now() to get millisecondds since epoch
var start = Date.now();
// ... Some time later
var diff = Date.now() - start; // milliseconds since start
How do I calculate the difference in minutes given two strings. For example say I have
11:00
11:30
But of course the second string could be 12:11 so I can't subtract just the minutes.
first use javascript to convert the strings to time, then subtract, then convert back to strings
like this:
x = new Date("1/1/01 11:00")
y = new Date("1/1/01 11:30")
// now y-x has difference in milliseconds
// (y-x)/1000 is difference in seconds, etc
The data 1/1/01 is just being used as a dummy value, but the one thing you might have to worry about is are the times on different days, if so you will have to use 1/2/01 for the second time. Unless of course you always know the times are in the same day, but if they can cross "midnight" then you have to adjust for that.
You may want to use http://momentjs.com/ which will take care of the details for you.
When looking for getting metrics such as date , hour , minutes, seconds from the date difference, it's a lot easier to use basic notations as listed here
var x = new Date(new Date().getTime() + 11.5*60*60000); // adds 11 hours - 30 minutes
var y = new Date(new Date().getTime() + 11*60*60000); // adds 11 hours
alert(x.getMinutes() - y.getMinutes()); // gives the difference = 30
Here's an example : https://jsfiddle.net/DinoMyte/157knmgn/
im tryng to create a system that open and close rounds in some date and time for users to play.
The problem is that javascript is not beeing precise, some times its faling to make the change in the correct time, and just change 1 minute later.
Maybe the problem is becouse I am geting de original date in UTC and converting before compare this date with the actual date and time...
I try compare using >=, just <, using .getTime(), but the problem is the same, javascript dont detect when the times are equal, the comparing only works 1 minute later, when one date is minor or greater than other.
This is the last code:
round_ended = new Date(round.ended + 'Z');
var date = new Date();
if (date.getTime() >= round_ended.getTime()) {
round.phase = "closed";
}
As I say, i have tried, with no success, other variations like this:
round_ended = new Date(round.ended + 'Z');
var date = new Date();
if (!(date < round_ended)) {
round.phase = "closed";
}
Someone can help?
What if you compare date ISO Strings.
if (!(date.toISOString() < round_ended.toISOString())) {
round.phase = "closed";
}
The ISO format is fixed : YYYY-MM-DDTHH:mm:ss.sssZ
I still dont no exactly the problem, but i guess is the miliseconds.
So, i found a solution based on this guess.
I compare the difference of the two values and check if it is smaller than 1000:
var time = round_ended - date;
if (time < 1000) {
round.phase = "closed";
}
Now it work's fine.
Thanks for the help.
While selecting current date,show the message as You cannot select a day earlier than today.
function checkDate(sender, args) {
if (sender._selectedDate) < new Date()) {
alert("You cannot select a day earlier than today!");
sender._selectedDate = new Date();
sender._textbox.set_Value(sender._selectedDate.format(sender._format))
}
}
Comparison is not working properly.
Please help me.
I'm guessing that your sender._selectedDate has 0 for its hours, minutes, seconds, and milliseconds. The new Date() you are comparing it to will have hours, minutes, seconds, and milliseconds set to the current time, which is likely later than the _selectedDate. So, you should create the new date, and then set its hours, minutes, seconds, and milliseconds to 0. Then you can compare the dates properly. You can use setHours(), and pass in hours, minutes, seconds, and milliseconds. Also, thanks to #andrex for noticing that you also have a syntax error: remove the ) after `sender._selectedDate.
function checkDate(sender, args) {
var earliestDate = new Date();
earliestDate.setHours(0,0,0,0);
if (sender._selectedDate < earliestDate) {
alert("You cannot select a day earlier than today!");
sender._selectedDate = earliestDate;
sender._textbox.set_Value(sender._selectedDate.format(sender._format));
}
}
Not sure what the data of the date verification is used for so several solutions spring to mind.
Anyway I would divide the dates into its parts as (year/month/day/hours) etc and (+/-) find out if one or the other (year/month/day/hours) etc. doesnt compare or is earlier cq later then your checksum variable.
I gather you want to compare only (year/month/day) realy so when those check to be valid discard the rest!
var dag = nu.getDate();
var wkdag = nu.getDay();
var maand = nu.getMonth();
var jaar1 = nu.getYear();
btw. Thinking about it, it makes a whole lot of difference if the form is checked right away or later, since more time that passes between validation of the function and sending the message, more chance of the date being earlier, if checked right away and using server time least chance of errors, but even then if send at 24:00 hours, validation of the date cq day will be done the next day. You may think of some code to put a stopper in the hole!