Do something when time is above the set time - javascript

I am just a newbie. I am trying delete a span when the time is above 6:30 pm daily. Code below:
(function(){
var d = new Date();
d.setHours(18,30,0);
if (d<new Date().toLocaleString());{
$("span:contains('Material Receive')").remove()
return false;}})();
However it s not working. It is always removing, i.e 24x7.

getHours Method will fit perfect i think
var d = new Date();
if (1830 < d.getHours()+""+d.getMinutes()){
$("span:contains('Material Receive')").remove()
return false;
}

Try to not compare an object with a string. Use 2 numbers instead. And lose the stray semicolon.
if (d.getTime() < new Date().getTime()){...}

Above answers already explained for you. Anyway:
Getting current date and time in JavaScript
I didn't understand exactly what you want to do, I suppose to delete a span every day at 18:30, right?
In this case, when you create the date object, you have to access hours and minutes to check time so:
( function() {
var d = new Date();
if( ( d.getHours() == 18 ) && ( d.getMinutes() == 30 ) ) {
$("span:contains('Material Receive')").remove();
return false; //Useless in a self-invoking function
}
})();

Related

Trying to remove all the passed dates

I have an array with many dates, they are not in the date type but string like: "2016-08-12" for example. Then what I would like to do is to remove all dates that we already have passed. So therefor im trying to compare them to todays date and then remove it if its passed. Using typescript by the way.
my array, named datoArray, looks like this:
["2016-08-02", "2016-08-11", "2016-08-22", "2016-09-10"]
just with a lot more of the same...
then here's what I try to do:
for(var i = 0; i < this.datoArray.length; i++){
this.skoleAar = parseInt(this.datoArray[i].slice(0,4))
this.skoleMaaned = parseInt(this.datoArray[i].slice(5,8))
this.skoleDag = parseInt(this.datoArray[i].slice(8,10))
if(this.skoleAar < dagensAar){
this.datoArray.splice(i, 1);
}
if(this.skoleAar == dagensAar && this.skoleMaaned < dagensMaaned){
this.datoArray.splice(i, 1);
}
if(this.skoleAar == dagensAar && this.skoleMaaned == dagensMaaned && this.skoleDag < dagensDag){
this.datoArray.splice(i, 1);
}
}
the "dagensAar", "dagensMaaned" and "dagensDag" variables im getting from another function that works. If i "console.log" the variables it prints out int values like 2016 for the year and 8 for the month if i take from the start of the array, and for the "dagensAar", "dagensMaaned" and "dagensDag" it prints 2016 11 20, which is todays year, month and day. all is in Int type, so what im not getting here is why my "if" doesnt work? It seems like there is something wrong with the way i compare the, but i thought this was the way to compare int values?
If the dates are in ISO-8601 format then you can simply filter using Date.parse().
var dates = ["2016-08-02", "2016-08-11", "2016-08-22", "2016-09-10", "2016-12-15"];
function removePastDates(data) {
var today = new Date();
console.log('Initial state: ' + data);
var modified = dates.filter(function(dateString) {
return Date.parse(dateString) >= today;
});
console.log('Final state: ' + modified);
return modified;
}
var newDates = removePastDates(dates);
Your dates seem to be RFC compliant, meaning they can be directly fed into a new Date object. Simply compare to today and filter by that:
var today = new Date()
var futureDates = this.datoArray.filter(d => new Date(d) >= today)
(pre-ECMA6:)
var today = new Date()
var futureDates = this.datoArray.filter(function (d) {
return new Date(d) >= today;
})
I think the problem is not related to the dates.
I think the problem is that you are removing items from the array while looping the same exact array.
You should maybe try looping from the end of the array to the beginning or just save the indexes that you need to remove and later do the actual removing.
Keep in mind that when you remove an item you change the index of every item in the remaining of the array - maybe you should start removing from the greatest index so it will not confuse you.

Monkeypatch the JavasScript date object

I know that this a crazy hack but curious about it anyhow. We have an environment that has the wrong system time and we cannot set it to the correct time. It's specialized hardware so we cannot change the system time. We do however have a service that gives us the correct current time. Our issue is that a bunch of ssl and token signing libraries break because they are getting the wrong datetime from the javascript Date object ( since we have the wrong system time).
What's the way to monkeypatch the Date object's constructor so that we can feed it the correct time to initialize with so that all subsequent calls to Date(), Date.toString(), etc... in the dependent libraries will return our new method that returns the correct non-system time?
Will this work?
var oldDate = Date;
Date = function(){
return new oldDate(specialCallToGetCorrectTime());
}
Date.prototype = oldDate.prototype;
Will this work?
No, since it does not respect arguments given to your new Date function or whether it was called as a constructor vs not. Also you forgot to fix Date.now(). You still will need to get those right:
Date = (function (oldDate, oldnow) {
function Date(year, month, date, hours, minutes, seconds, ms) {
var res, l = arguments.length;
if (l == 0) {
res = new oldDate(Date.now());
} else if (l == 1) {
res = new oldDate(year); // milliseconds since epoch, actually
} else {
res = new oldDate(
year,
month,
l > 2 ? date : 1,
l > 3 ? hours : 0,
l > 4 ? minutes : 0,
l > 5 ? seconds : 0,
l > 6 ? ms : 0)
}
if (this instanceof Date) {
return res;
} else {
return res.toString();
}
}
Date.prototype = oldDate.prototype; // required for instanceof checks
Date.now = function() {
return oldnow() + offset; // however the system time was wrong
};
Date.parse = oldDate.parse;
Date.UTC = oldDate.UTC;
return Date;
})(Date, Date.now);
I just tried this out in the latest Chrome, Firefox, and IE, and it is allowed. I'm not convinced this is better than just fixing the system time (surely it can be fixed), but the approach is doable.
Yes, provided the implementation allows you to redefine window.Date
(It's polite to wrap this sort of thing in a closure)

How to add one second to a time string with javascript/jquery

I am trying to create a timer with Javascript but I don't know how to add one second to a time string.
Time string: 03:31:15
function updateWorked() {
var time = $("#worked").html();
???
$("#worked").html(wtime);
}
$(document).ready(function() {
setInterval('updateWorked()', 1000);
});
What should I write in "???" to make this work?
Assuming you are using something like PHP to get the time string in the first place, and you can't keep track of the date/time as a number as suggested by Marc B, you can parse the string yourself like this:
var $worked = $("#worked");
var myTime = $worked.html();
var ss = myTime.split(":");
var dt = new Date();
dt.setHours(ss[0]);
dt.setMinutes(ss[1]);
dt.setSeconds(ss[2]);
var dt2 = new Date(dt.valueOf() + 1000);
var ts = dt2.toTimeString().split(" ")[0];
$worked.html(ts);
Edit: Working jsFiddle here of this code.
Here's the code with a timer: jsFiddle
Below is an example on how to add a second to a time string. You can use the date object to print out the string in any format that you would like, in this example i'm just using the build in toTimeString method.
var timeString = "10/09/2012 14:41:08";
// start time
var startTime = new Date(timeString);
// prints 14:41:08 GMT-0400 (EDT)
console.log(startTime.toTimeString())
// add a second to the start time
startTime.setSeconds(startTime.getSeconds() + 1);
// prints 14:41:09 GMT-0400 (EDT)
console.log(startTime.toTimeString())
If you're trying to keep a counter in real time, you should use new Date() to get the time, and then format it:
function updateWorked() {
var time = new Date(),
wtime = formatDate(time);
$("#worked").html(wtime);
}
However, if you're trying to keep a specific time, then you should up-scope a Date object and use that:
var time = new Date(/* your starting time */);
function updateWorked() {
time.setTime(time.getTime()+1000);
var wtime = formatDate(time);
$("#worked").html(wtime);
}
Also, you'd want to add a formatDate function:
function formatDate(date) {
var hours = date.getHours().toString();
if (hours.length < 2) hours = '0'+hours;
var minutes = date.getMinutes().toString();
if (minutes.length < 2) minutes = '0'+minutes;
var seconds = date.getSeconds().toString();
if (seconds.length < 2) seconds = '0'+seconds;
return hours+':'+minutes+':'+seconds;
}
Using mixture of jquery and javascript you can achieve this example.
I tired to achive what you looking for, first created a date object and get all the values of time, minute and second and then replaced the value.
Please have a look at jsfiddle
DEMO
http://jsfiddle.net/saorabhkr/xtrpK/

jQuery string Comparison?

I'm comparing two dates and my code goes like this.
jQuery('.newAppointment a.ui-state-default').click(function() {
var date = jQuery(this).parent().attr('title');
var d = jQuery.datepicker.parseDate('dd/mm/yy',date.toString());
alert(d);
var today = new Date;
var t = jQuery.datepicker.parseDate('dd/mm/yy',today.toString() );
alert(t)
if(t > d){
url = "/users/" + user_id + "/events/new?type=Surgery"+"&day=" + escape(date);;
window.location = url;
}else{
alert("you cannot add appointment to past dates");
}
});
but am getting error in firebug.
uncaught exception: Missing number at position 0
can anyone tell me where I'm doing wrong.
From the fine manual:
parseDate(format, value, settings)
[...]
A number of exceptions may be thrown:
'Missing number at position nn' if format indicated a numeric value that is not then found
So your error is coming from jQuery-UI. The format you get from date.toString() depends on the browser and the locale, there's no reason to expect it always be dd/mm/yy and in your case, it isn't.
Your date is already a string and in a known format (presumably dd/mm/yy) so you should be able to do this:
var d = jQuery.datepicker.parseDate('dd/mm/yy', date);
to get a Date. Then you can get today with just:
var today = new Date;
and compare them directly:
if(today > d)
If you want to throw away the hours, minutes, and seconds then:
var now = new Date;
// Or set milliseconds, seconds, minutes, and hours to zero.
var today = new Date(now.getFullYear(), now.getMonth(), now.getDate());
if(today > d)
may be there is some problem with parseDate()
You can compare the dates just by using just
if (today > date){...}

Time not displayed

alert("hello");
var d = Date();
//alert(d);
var currHour = d.getHours();
document.write(currHour);
function display1(currHour) {
if(currHour > 1) {
alert("good morning");
} else {
alert("ok bye" + currHour);
}
}
The hello alert shows fine, date also shows fine, however currHour is undefined i don't know
what am I doing wrong here.
Thanks.
var d = new Date();
You are missing the new keyword. new [MDN]
Example
Per ECMA-262 section 15.9.2, the Date constructor, when called as a function, returns a String representing the current time (UTC).

Categories

Resources