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.
Related
This question already has answers here:
JavaScript Date Object Comparison
(7 answers)
Closed 2 years ago.
I'm trying to check dates in Javascript for a calendar (fullcalendar), essentially I just want it to not be able to choose past dates:
dateClick: function(info) {
var today = Date.now();
var check = new Date(info.dateStr)
if(check < today)
{
alert('You cannot request dates in the past');
return;
}
else
{
alert('this is the future');
}
},
I'm getting some odd results in that, it seems to calculate the past fine, but also calculates the current day as the past AS well as tomorrow. The day after tomorrow it calculates as the future. No sure what's going on.
info.dateStr gives the format YYYY-mm-dd.
You should coerce to number using +Date or use .getTime() to make sure you are comparing the numeric timestamp values. You're probably fine since you're using Date.now(), which returns a timestamp.
Parsing using the string parsing for Date is strongly discouraged, due to issues like the one in OP:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/Date
Use Date(yyyy, mm, dd, ...) constructor (which uses local time zone) by parsing string manually instead of built-in Date string parsing (which uses UTC if timezone isn't provided).
Using end of the day by adding 24*60*60*1000 to the getTime() value, as that's most likely what you're expecting (same date as today being past is not what most people usually want).
eg: with date to check 05-29-2020, you actually want anything before 05-29-2020 23:59:999
ie: check=05-29-2020 23:59:999 < today=05-29-2020 22:00:000 === false (not past)
or to put it another way the actual intention when:
05-29-2020 => anything from 05-29-2020 00:00 to 05-29-2020 23:59 => actually same as checking 05-30-2020 00:00 - 1 millisecond
dateClick = function(info) {
var today = Date.now()
var check = (([y,m,d])=>new Date(+y,+m-1,+d))(info.dateStr.split(/\D/)).getTime()
+ 24*60*60*1000-1 // add full day so same date as today is not past
console.log(today,check)
if(check < today)
{
alert('You cannot request dates in the past');
return;
}
else
{
alert('this is the future');
}
}
dateClick({dateStr:'2020-05-28'})
dateClick({dateStr:'2020-05-29'})
dateClick({dateStr:'2020-05-30'})
dateClick({dateStr:'2020-05-31'})
you want to compare dates like this: date1.getTime() - date2.getTime()
also, keep in mind, if your goal is to make sure a user is inputing a date that is not in the past, you can use html5 date input with a min set:
<input type="date" min="2020-05-29">
I am trying to have a date entry box which has the following restrictions. Date must be today's date or earlier, but not more than 1 year previous. I have the following line:
if (myFDGDT - todayDate > 0 || (myFDGDT - todayDate)/86400000 < -365)
The first portion of that creates the appropriate alert when some enters a date after today's date. Not sure about the best way to cap the entry to a year previous. Attempted a few items, but the above was just an example of my last attempt. This is also written in a dependency and not in the Global JavaScript of our entry client.
Here is a snippet that will generate a Date object that is one year ago. You can compare against it as needed using greater than/less than operators.
var oneyear = new Date('01/01/1971'); // from unix epoch
var now = new Date();
var oneyearago = new Date(now - oneyear);
alert(oneyearago);
If you are manipulating dates a lot in your app you should consider using the momentjs library. For your problem the solution would be something like:
var momentdate = moment(date);
if (momentdate.isAfter(momentdate.add(1, 'year') ||
momentdate.isBefore(momentdate.startOf('day')) {
// Invalid date?
}
Hope this helps.
I want to get start and enddates for upcoming 4 weeks(only weekdays).
Suppose today's date is 2015-12-01 then the result should be as below
Week0 will have StartDate = 2015-11-30 and EndDate = 2015-12-04
Week1 will have StartDate = 2015-12-07 and EndDate = 2015-12-11
Week2 will have StartDate = 2015-12-14 and EndDate = 2015-12-18
Week3 will have StartDate = 2015-12-21 and EndDate = 2015-12-25
Here date of Week0 should be calculated from current date.
Try the moment library. It's pretty easy to use, so you should be able to figure out quickly, how to do this.
var date = moment(yourdate);
// iterate by date.add(1, "week")
var start = date.clone().startOf('week');
var end = date.clone().endOf('week');
//use .format('YYYY-MM-DD'); to print out
Here is how you would use the Moment.js library (as mentioned in the comments) to achieve the output you desire. It's quite easy by using the built in functions (to see the result, hit F12 on your keyboard or open the console some other way)
var weeks = 4;
for (var i = 0 ; i < weeks ; i++) {
var start = moment().startOf('isoweek').add(i, 'weeks');
var end = start.clone().add(4, 'days');
console.log("Week%d will have StartDate = %s and EndDate = %s", i, start.format('YYYY-MM-DD'), end.format('YYYY-MM-DD'));
}
<script src="http://momentjs.com/downloads/moment.min.js"></script>
Couple simple built in functions at work here, namely:
moment, which is an instance of the moment class - essentially a datetime string.
startOf, pretty self explanatory, finds the exact datetime of when (in this case) the start of the week was
add, which adds a certain amount of x i.e. days, weeks, months etc. to the moment instance
clone, a necessary step which clones the original moment to prevent it from being modified by the end variable.
and format, pretty obvious, formats the moment based on the string given as its argument.
Take a look at the Moment.js docs and have a little decipher of the code; it will help you understand Moment.js as a library much better. Hope this helps.
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.
I want to compare strings that are dates
if (user_date < date)
date has yyyy-mm-dd format, so it is OK to compare dates as strings, if the user enters a valid user_date in this format.
Unfortunately, user_date is entered by the user, so it could be invalid. In case if it is invalid (or left empty), I want (user_date < date) always to be true.
I have found to set var user_date=''; if user's date is invalid. Is that a good way to make make (user_date < date) for any valid date?
The same question is for (user_date > date) (more than any date).
I've found to set var user_date='A';
I need it for
if (date1 <= date && date2>= date)
//do something
So it works without any additional if then.
P.S. I don't want to enter var user_date='2222-12-31'; because the algorythm will stop working properly in less than 210 years.
I think that is not possible. But what is possible is to get a date for which a comparison is always false — so functionally it behaves the same as NaN does for numbers. So if you invert the test, thus replace (a <= b) with !(a > b), it would work.
$date = new Date(NaN);
if (!($date1 > $date) && !($date2 < $date)) ...
p.s. What's with the dollar signs? Are you confusing Javascript with PHP or Perl? :)
Why not set your min to be 0000-01-01 and your max to be 9999-12-31 ?
I think you can do somethin glike
var date = '2013-03-12';
var $date = new Date(date);
function onChange(el){
var user_date = el.value;
var udate = new Date(user_date);
if(isNaN(udate.getTime()) || udate < $date){
alert('less')
}
}
Demo: Fiddle
Personally I would first validate the date that the user is entering - don't leave it to chance.
I use my own date extensions library here for this kind of stuff:
DP_DateExtensions
The parseFormat() method will let you easily validate your input. Something like this so do well:
Date.parseFormat(InputString, "YYYY-M-D")
The function returns a valid JavaScript date if the entered string matches the format or null if it doesn't. You obviously don't have to send a user message based on this if you have a default behavior you'd like to apply - but the code itself should "know".
In this case - if you want an invalid date to be less than another, known good date, then there are many ways to do it. Most simple is something like this:
InputDate = Date.parseFormat(InputString, "YYYY-M-D");
if ( InputDate || InputDate < GoodDate ) {
Input Date is Invalid or Falls before good date
} else {
Input Date is Falls after good date
};
You don't need to set "false dates" or guess with the right validation and Boolean logic in play and it will work until the world stops spinning (in theory).
You can you use the compare() method in the library to do any kind of greater/less than comparison to any precision.
Hope this helps.