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).
Related
I'm new to typescript. I wrote this code to get the next three working days(Sunday is not a working day). But it is not working. Can someone suggest an alternative solution?
today = new Date()
day1 = get_next_working_day(today)
day2 = get_next_working_day(day1)
day3 = get_next_working_day(day2)
function get_next_working_day(day){
const temp = new Date(day.setDate(day.getDate()+1) )
if(temp.getDay() == 0){
return get_next_working_day(temp)
}
return temp
}
When you call setDate on a date, it modifies the date object itself. So your code will always change today's date to be tomorrow. Try this instead
function get_next_working_day(day){
const temp = new Date(day);
temp.setDate(temp.getDate()+1);//Modifies temp valur
if(temp.getDay() == 0){
return get_next_working_day(temp);
}
return temp;
}
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
}
})();
Could anyone please explain the below code to me?
For example, i would like to set Today's date to today (21st of November, 2012) and the end date to the 3rd of December.
The reason for this is because i want to loop through a list of items, determine whether they are in the "past", "present" or "future" and assign a class to them accordingly.
I hope this makes sense! Any help is greatly appreciated and much welcomed!
function daysTilDate(expiredate){
expiredate ="12/"+expiredate+"/2012";
var thisDay=new Date(expiredate);
var CurrentDate = new Date();
var thisYear=CurrentDate.getFullYear();
thisDay.getFullYear(thisYear);
var DayCount=(thisDay-CurrentDate)/(1000*60*60*24);
DayCount=Math.round(DayCount);
return DayCount;
}
You can simplify the method like below if you want to calculate the days to an expire date. Please note that if you don't specify a test date, it'll take the current date as the test date.
​function ​daysTilData(expireDate, testDate) {
if(typeof testDate === "undefined"){
testDate = new Date(); // now
}
var diff = expireDate - testDate;
// minus value meaning expired days
return Math.round(diff/(1000*60*60*24));
}
alert(daysTilData(new Date("12/31/2012")));
// result 40
alert(daysTilData(new Date("12/31/2012"), new Date("1/12/2013")));
// result -12
Here's a line by line explanation.
The function declaration...
function daysTilDate(expiredate){
Takes the parameter expiredate sets it equal to the same value with "12/" prepended and "/2012" appended. so if the value of expiredate was "10", the new value is now "12/10/2012"...
expiredate ="12/"+expiredate+"/2012";
Instantiates a new Date object named thisDay using the expiredate string...
var thisDay=new Date(expiredate);
Instantiates a new Date object named CurrentDate, using the default constructor which will set the value equal to today's date...
var CurrentDate = new Date();
Gets just the Year segment from CurrentDate (which was earlier set to today's date)...
var thisYear=CurrentDate.getFullYear();
Gets the Year segment from thisDay (which was earlier set to "2012")...
thisDay.getFullYear(thisYear);
Gets the difference between thisDay and CurrentDate, which is in milliseconds, and multiplies that by 1000*60*60*24 to get the difference in days...
var DayCount=(thisDay-CurrentDate)/(1000*60*60*24);
Rounds the previously calculated difference...
DayCount=Math.round(DayCount);
Returns the difference between today and the passed-in day in December 2012...
return DayCount;
}
Note that the 2 lines that get the year segments are extraneous, because those values are never used...
I am not going to review the code, but I can answer your question of "I want to loop through a list of items, determine whether they are in the past, present, or future".
First, you want to construct your target date. If it's "now", just use new Date(). If it's a specific date, use new Date(dateString).
Second, Date objects in JavaScript have various members that return the date's characteristics. You can use this to compare dates. So, let's say you have your date strings in an array:
function loopDates(targetDateString, myDates) {
var targetDate, nextDate, status, ix;
targetDate = new Date(targetDateString);
for (ix = 0; ix < myDates.length; ++ix) {
nextDate = new Date(myDates[ix]);
if (nextDate.getFullYear() < targetDate.getFullYear()) {
status = "past";
} else if (nextDate.getFullYear() > targetDate.getFullYear()) {
status = "future";
} else {
// Year matches, compare month
if (nextDate.getMonth() < targetDate.getMonth()) {
status = "past";
} else if (nextDate.getMonth() > targetDate.getMonth()) {
status = "future";
} else {
// Month matches, compare day of month
if (nextDate.getDate() < targetDate.getDate()) {
status = "past";
} else if (nextDate.getDate() > targetDate.getDate()) {
status = "future";
} else {
// Day matches, present
status = "present";
}
}
}
console.log("Date " + myDates[ix] + " is " + status + " from " + targetDateString);
}
}
loopDates("11/17/2012", ["11/16/2012", "11/17/2012", "11/18/2012"]);
This will log:
Date 11/16/2012 is past from 11/17/2012
Date 11/17/2012 is present from 11/17/2012
Date 11/18/2012 is future from 11/17/2012
Working jsFiddle here.
If you want to work with a comprehensive Date class, use DateJS, an open source JavaScript date and time processing library with some impressive features.
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/
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){...}