PDA

View Full Version : Date with greetings



FrickenTrevor
10-07-2014, 07:50 AM
Hey there, I am horrible with JavaScript but trying to learn it. Anyways I have some (horrible) javascript written where based on the computers time would display a greeting along with the time and change the background according to the time. This is what I have so far




var Digital=new Date();
var hours=Digital.getHours();

/* Live Date script from Dynamic Drive */

var dayarray=new Array("Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday")
var montharray=new Array("January","February","March","April","May","June","July","August","September","October","November","December")

function getthedate(){
var mydate=new Date()
var year=mydate.getYear()
if (year < 1000)
year+=1900
var day=mydate.getDay()
var month=mydate.getMonth()
var daym=mydate.getDate()
if (daym<10)
daym="0"+daym
var hours=mydate.getHours()
var minutes=mydate.getMinutes()
var seconds=mydate.getSeconds()
var dn="AM"
if (hours>=12)
dn="PM"
if (hours>12){
hours=hours-12
}
if (hours==0)
hours=12
if (minutes<=9)
minutes="0"+minutes
if (seconds<=9)
seconds="0"+seconds

/*End Live Date script */

if (hours>=5&&hours<=11) {
document.write('Good morning! It is now '+time+' on '+date+');}

// I have no idea how to do variables. Basically print something like this:
//
// Good morning! It is now
//
// 9:12:32 A.M.
// Saturday, January 12th, 2014
//
//
// Then somehow have the background of the page a photo of a sunrise (lets call that photo sunrise.jpg)


else if (hours==12) {
document.write('Lunch time!');}

else if (hours>=13&&hours<=17) {
document.write('Good afternoon');}

else if (hours>=18&&hours<=20) {
document.write('Good evening');}

else if (hours>=21&&hours<=11) {
document.write('Its late.');}

else {
document.write('Hello night-owl!');}

vwphillips
10-07-2014, 12:05 PM
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">

<html>

<head>
<title></title>
</head>

<body>
<script type="text/javascript">
<!--
var Digital=new Date();
var hours=Digital.getHours();

/* Live Date script from Dynamic Drive */

var dayarray=["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"];
var montharray=["January","February","March","April","May","June","July","August","September","October","November","December"];

function getthedate(){
var mydate=new Date(2014,9,7,7);
var year=mydate.getFullYear();
var day=mydate.getDay();
var month=mydate.getMonth();
var daym=mydate.getDate();
if (daym<10)
daym="0"+daym;
var hours=mydate.getHours();
var minutes=mydate.getMinutes();
var seconds=mydate.getSeconds();
var dn="AM";
if (hours>=12)
dn="PM";
if (hours>12){
hours=hours-1;2
}
if (hours==0)
hours=12;
if (minutes<10)
minutes="0"+minutes;
if (seconds<=9)
seconds="0"+seconds;

if (hours>=5&&hours<=11) {
var date=mydate.getDate()+'';
var d=date.charAt(0);
document.write('Good morning! It is now <br><br>'+(hours+':'+minutes+':'+seconds+dn)+'<br>'+(dayarray[mydate.getDay()]+', '+montharray[mydate.getMonth()]+' '+date+(d=='1'?'st':d=='2'?'nd':d=='3'?'rd':'th')+' '+year));
// document.body.style.backgroundImage='url(http://www.vicsjavascripts.org/StdImages/1.gif)';
// I have no idea how to do variables. Basically print something like this:
//
// Good morning! It is now
//
// 9:12:32 A.M.
// Saturday, January 12th, 2014
//
//
// Then somehow have the background of the page a photo of a sunrise (lets call that photo sunrise.jpg)

}

else if (hours==12) {
document.write('Lunch time!');
}

else if (hours>=13&&hours<=17) {
document.write('Good afternoon');
}

else if (hours>=18&&hours<=20) {
document.write('Good evening');
}

else if (hours>=21&&hours<=11) {
document.write('Its late.');
}

else {
document.write('Hello night-owl!');
}
/*
*/

}
getthedate();
//-->
</script>
</body>

</html>

FrickenTrevor
10-08-2014, 07:27 PM
Why is the time stuck at 7 Am though? Heres a demo from Code Pen (http://codepen.io/anon/pen/qJGwb)

james438
10-08-2014, 09:10 PM
var mydate=new Date(2014,9,7,7);

I do not know javascript very well at all either, but in the above line you will see that it reads September 7, 2014 at 7am. The problem is that the output is October.

I'll leave the real answer to vwphillips or jscheuer1 though :)

FrickenTrevor
10-09-2014, 12:41 AM
The problem is that the output is October.

The problem is also that the date and time is preset, I can't figure out how to get the current date and time

Edit:

I'll leave the real answer to vwphillips or jscheuer1 though :)

I think is jscheuer1 is busy at this post (http://www.dynamicdrive.com/forums/showthread.php?76326-Next-button-for-scroll-code), among others.

james438
10-09-2014, 05:31 AM
There are errors, but less than before. As a reminder, my knowledge of javascript is near absolute beginner.


var Digital=new Date();
var hours=Digital.getHours();

/* Live Date script from Dynamic Drive */

var dayarray=["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"];
var montharray=["January","February","March","April","May","June","July","August","September","October","November","December"];

function getthedate(){
var mydate=new Date();
var year=mydate.getFullYear();
var day=mydate.getDay();
var month=mydate.getMonth();
var daym=mydate.getDate();
if (daym<10)
daym="0"+daym;
var hours=mydate.getHours();
var minutes=mydate.getMinutes();
var seconds=mydate.getSeconds();
var dn="AM";
if (hours>=12)
dn="PM";
if (hours>12){
hours=hours-12;
}
if (hours===0)
hours=12;
if (minutes<10)
minutes="0"+minutes;
if (seconds<=9)
seconds="0"+seconds;

if (hours>=5&&hours<=11) {
var date=mydate.getDate()+'';
var d=date.charAt(0);
document.write('Good morning! It is now <br><br>'+(hours+':'+minutes+':'+seconds+dn)+'<br>'+(dayarray[mydate.getDay()]+', '+montharray[mydate.getMonth()]+' '+date+(d=='1'?'st':d=='2'?'nd':d=='3'?'rd':'th')+' '+year));
// document.body.style.backgroundImage='url(http://www.vicsjavascripts.org/StdImages/1.gif)';
// I have no idea how to do variables. Basically print something like this:
//
// Good morning! It is now
//
// 9:12:32 A.M.
// Saturday, January 12th, 2014
//
//
// Then somehow have the background of the page a photo of a sunrise (lets call that photo sunrise.jpg)

}

else if (hours==12) {
document.write('Lunch Time! It is now <br><br>'+(hours+':'+minutes+':'+seconds+dn)+'<br>'+(dayarray[mydate.getDay()]+', '+montharray[mydate.getMonth()]+' '+date+(d=='1'?'st':d=='2'?'nd':d=='3'?'rd':'th')+' '+year));
}

else if (hours>=13&&hours<=17) {
document.write('Good afternoon! It is now <br><br>'+(hours+':'+minutes+':'+seconds+dn)+'<br>'+(dayarray[mydate.getDay()]+', '+montharray[mydate.getMonth()]+' '+date+(d=='1'?'st':d=='2'?'nd':d=='3'?'rd':'th')+' '+year));
}

else if (hours>=18&&hours<=20) {
document.write('Good evening! It is now <br><br>'+(hours+':'+minutes+':'+seconds+dn)+'<br>'+(dayarray[mydate.getDay()]+', '+montharray[mydate.getMonth()]+' '+date+(d=='1'?'st':d=='2'?'nd':d=='3'?'rd':'th')+' '+year));
}

else if (hours>=21&&hours<=11) {
document.write('It is late! It is now <br><br>'+(hours+':'+minutes+':'+seconds+dn)+'<br>'+(dayarray[mydate.getDay()]+', '+montharray[mydate.getMonth()]+' '+date+(d=='1'?'st':d=='2'?'nd':d=='3'?'rd':'th')+' '+year));
}

else {
document.write('Hello night owl! It is now <br><br>'+(hours+':'+minutes+':'+seconds+dn)+'<br>'+(dayarray[mydate.getDay()]+', '+montharray[mydate.getMonth()]+' '+date+(d=='1'?'st':d=='2'?'nd':d=='3'?'rd':'th')+' '+year));
}
/*
*/

}
getthedate();

FrickenTrevor
10-09-2014, 11:12 PM
my knowledge of javascript is near absolute beginner.

Same with me, I wish I could find someone on these forums who could help

james438
10-10-2014, 01:47 AM
Did the above not answer your question?

jscheuer1
10-10-2014, 03:25 AM
Let's see, this should work (does in moderate testing here). There might be a slight learning curve. I will explain the essentials, then - if there are any questions, please ask. First the code, please notice the highlighted part near the end:


<!DOCTYPE html>
<html>
<head>
<title>Time Driven Events Demo</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<script type="text/javascript">
// Time Driven Events Script (c)2014 John Davenport Scheuer
// as first seen in http://www.dynamicdrive.com/forums/
// username: jscheuer1 - This Notice Must Remain for Legal Use
var timedriver = {
setrange: function(strt, end, msg, action){
strt = strt.toString(10).split(':');
end = end.toString(10).split(':');
if (!(this.hrs >= strt[0] && this.hrs <= end[0])) {return;}
if (this.hrs == strt[0] && strt[1] && strt[1] < this.mns) {return;}
if (this.hrs == end[0] && end[1] && this.mns >= end[1]) {return;}
this.setmsgel();
if(this.msgel){
this.msgel.innerHTML = msg.join(this.h + ':' + this.m + this.suffix);
}
action && action();
},
setmsgel: function(){
return this.msgel || (this.msgel = document.getElementById(this.elid));
},
now : new Date(),
hours: function(){return this.h = this.hrs = this.now.getHours();},
mins: function(){return this.m = this.mns = this.now.getMinutes();},
ampm: function(){
this.suffix = this.hrs > 11? 'pm' : 'am';
this.h = this.hrs > 11? this.hrs - 12 : this.hrs;
this.m = this.mns > 9? this.mns : '0' + this.mns;
return this.suffix;
},
init: function(){
this.hours();
this.mins();
this.ampm();
return this;
}
};
</script>
</head>
<body>
<div id="timemsg"></div>
<script type="text/javascript">
var mytime = timedriver.init();
mytime.elid = 'timemsg';
mytime.setrange('0', '8', ["Good Morning! It's ", ", Up early, huh?"], function(){document.body.style.background = 'yellow';});
mytime.setrange('20', '21', ["Good Evening! It's ", ", Nice night, huh?"], function(){document.body.style.background = 'lightblue';});
mytime.setrange('22', '23:59', ["Good Night! It's ", ", Why are you still up?"], function(){document.body.style.background = 'blue';});
</script>
</body>
</html>

That (the highlighted) is what you will use (with modifications as desired) to accomplish your aims. Notice the red timemsg id for the div and how it's also used in the mytime.elid statement to tell the code the id of the element that you want the message to appear in.

Also please notice that you need to first initialize the code to a variable (in this example I've used - mytime). After that, anything else you do will be that variable.whatever, ex:


mytime.setrange

The real key here is that setrange command. It accepts a quoted start time in 24 hour notation. This can be in any of the normal formats, like 'h:mm', 'hh', 'hh:m', 'hh:mm', etc. Basically just hours, or hours and minutes separated by a colon. single or two digit hours may be used. same thing with the minutes (one or two digits as needed). Remember this is a string, so it must be quoted. This is when whatever you want to happen during this range of time begins. The next parameter is the end time. Same format as for start. It's when this range is no longer valid (if the current time is after or equal to end, this range will not execute). Next comes the message. It is an array with two members (before and after), ex:


["Good Evening! It's ", ", Nice night, huh?"]

You can have just a before:


["Good Evening! It's "]

or an empty before and just an after:


["", ", Nice night, huh?"]

What will be put in the 'middle' (location of the red comma, or at the end of a beginning only array) is the time in a format like:

10:01pm

Finally we have an action to perform. If there is none, nothing further will be done. If there is one, it must be a function, ex:


function(){document.body.style.background = 'blue';}

If you want to use a background image for the body of the page, that would be like:


function(){document.body.style.background = 'url: (myimage.jpg)';}

More complete instructions can be given, like positioning, repeat, etc. all according to the rules of css style and how they may be expressed in javascript. If you need further help with that - expressing just the sort of background - or anything else you might want in this function, just let me know.

FrickenTrevor
10-10-2014, 07:14 AM
The real key here is that setrange command. It accepts a quoted start time in 24 hour notation. .

How do I change it to 12 hour? As in 1:22 AM? Also what about for adding seconds and the date to the time string? My goal is to get something like this:




var dayarray=new Array("Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday")
var montharray=new Array("January","February","March","April","May","June","July","August","September","October","November","December")

function getthedate(){
var mydate=new Date()
var year=mydate.getYear()
if (year < 1000)
year+=1900
var day=mydate.getDay()
var month=mydate.getMonth()
var daym=mydate.getDate()
if (daym<10)
daym="0"+daym
var hours=mydate.getHours()
var minutes=mydate.getMinutes()
var seconds=mydate.getSeconds()
var dn="AM"
if (hours>=12)
dn="PM"
if (hours>12){
hours=hours-12
}
if (hours==0)
hours=12
if (minutes<=9)
minutes="0"+minutes
if (seconds<=9)
seconds="0"+seconds

if (hours>=5&&hours<=11) {
document.write('Good morning! It is now '+time+' on '+date+');}

// I have no idea how to do variables. Basically print something like this:
//
// Good morning! It is now
//
// 9:12:32 A.M.
// Saturday, January 12th, 2014
//
//
// Then somehow have the background of the page a photo of a sunrise (lets call that photo sunrise.jpg)


else if (hours==12) {
document.write('Lunch time!');}

else if (hours>=13&&hours<=17) {
document.write('Good afternoon');}

else if (hours>=18&&hours<=20) {
document.write('Good evening');}

else if (hours>=21&&hours<=11) {
document.write('Its late.');}

else {
document.write('Hello night-owl!');}

[/CODE]

jscheuer1
10-10-2014, 10:52 AM
It already output the time in 12 hour notation with an am/pm suffix. But it did need to be expanded to include all of the information about the date and time you request. I also added a fallback function (again see highlighted section) that will display when none of the ranges that are set qualify. The fallback should come before any setrange, because it will always fire, only to be replaced by a setrange if one qualifies. If more than one setrange qualifies, the later one (in order on the page not necessarily later in time) will win out. The setrange function requires 24 hour notation for its start and end times, as before. I repeat though, the output time is in 12 hour notation.


<!DOCTYPE html>
<html>
<head>
<title>Time Driven Events Demo</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<script type="text/javascript">
// Time Driven Events Script (c)2014 John Davenport Scheuer
// as first seen in http://www.dynamicdrive.com/forums/
// username: jscheuer1 - This Notice Must Remain for Legal Use
var timedriver = {
setrange: function(strt, end, msg, action){
strt = strt.toString(10).split(':');
end = end.toString(10).split(':');
if (!(this.hrs >= strt[0] && this.hrs <= end[0])) {return;}
if (this.hrs == strt[0] && strt[1] && strt[1] < this.mns) {return;}
if (this.hrs == end[0] && end[1] && this.mns >= end[1]) {return;}
//if (msg.length < 2) {msg[1] = '';}
this.setmsgel();
if(this.msgel){
this.msgel.innerHTML = msg[0] + //date output format:
[this.h, ':', this.m, ':', this.s, ' ', this.suffix, '<br>', this.d, ', ', this.mnth, ' ', this.dtth, ' ', this.y].join('')
+ (msg[1] || '');
}
action && action();
},
fallback: function(msg, action) {
this.setrange(this.hrs, this.hrs + 1, msg, action);
},
setmsgel: function(){
return this.msgel || (this.msgel = document.getElementById(this.elid));
},
now : new Date(),
year: function(){return this.y = this.now.getFullYear();},
month: function(){return this.mnth = ['January','February','March','April','May','June','July','August','September','October','November','December'][this.now.getMonth()];},
day: function(){return this.d = ['Sunday','Monday','Tuesday','Wednesday','Thursday','Friday','Saturday'][this.now.getDay()];},
date : function(){return this.dt = this.now.getDate();},
hours: function(){return this.h = this.hrs = this.now.getHours();},
mins: function(){return this.m = this.mns = this.now.getMinutes();},
secs: function(){return this.s = this.scs = this.now.getSeconds();},
th: ['', 'st', 'nd', 'rd'],
ampm: function(){
this.suffix = this.hrs > 11? 'PM' : 'AM';
this.h = this.hrs > 11? this.hrs - 12 : this.hrs;
this.m = this.mns > 9? this.mns : '0' + this.mns;
this.s = this.scs > 9? this.scs : '0' + this.scs;
this.dtth = this.dt + (this.th[this.dt] || (this.dt > 30? (this.th[this.dt - 30] || 'th') : this.dt > 20? (this.th[this.dt - 20] || 'th') : 'th'));
return this.suffix;
},
init: function(){
this.year();
this.month();
this.day();
this.hours();
this.mins();
this.secs();
this.date();
this.ampm();
return this;
}
};
</script>
</head>
<body>
<div id="timemsg"></div>
<script type="text/javascript">
var mytime = timedriver.init();
mytime.elid = 'timemsg';
mytime.fallback(["Hello! It's<br>"], function(){document.body.style.background = 'lightyellow';});
mytime.setrange('0', '8', ["Good Morning! It's<br>", ", Up early, huh?"], function(){document.body.style.background = 'yellow';});
mytime.setrange('20', '21', ["Good Evening! It's<br>", ", Nice night, huh?"], function(){document.body.style.background = 'lightblue';});
mytime.setrange('22', '23:59', ["Good Night! It's<br>", ", Why are you still up?"], function(){document.body.style.background = 'blue';});
</script>
</body>
</html>

Please at least copy this and run it without any modifications before asking further questions.

FrickenTrevor
10-11-2014, 12:04 AM
Thank you, I did run the code and it works. What part of the code could be changed so the seconds change? Not on page refresh but automatically Like 1:20:23 AM then 1:20:24 AM, 1:20:25 AM .....

jscheuer1
10-11-2014, 11:48 PM
Here's a new version (v2) It will cycle (update every second), or if you only want it to run once, use mytime.cycle(false) instead of mytime.cycle(). Here's the code:


<!DOCTYPE html>
<html>
<head>
<title>Time Driven Events Demo</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<script type="text/javascript">
// Updateable Time Driven Events Script v2 (c)2014 John Davenport Scheuer
// as first seen in http://www.dynamicdrive.com/forums/
// username: jscheuer1 - This Notice Must Remain for Legal Use
var timedriver = {
setrange: function(strt, end, msg, action){
if(strt === true){this.fallbacks.push([msg, action]);}
else{this.ranges.push(arguments);}
},
executerange: function(strt, end, msg, action){
strt = strt.toString(10).split(':');
end = end.toString(10).split(':');
if (!(this.hrs >= strt[0] && this.hrs <= end[0])) {return;}
if (this.hrs == strt[0] && strt[1] && strt[1] < this.mns) {return;}
if (this.hrs == end[0] && end[1] && this.mns >= end[1]) {return;}
this.setmsgel();
if(this.msgel){
this.msgel.innerHTML = msg[0] + [ //date output format:
this.h, ':', this.m, ':', this.s, ' ', this.suffix, '<br>', this.d, ', ', this.mnth, ' ', this.dtth, ' ', this.y
].join('') + (msg[1] || '');
}
action && action();
},
fallback: function(msg, action) {
this.setrange(true, '', msg, action);
},
setmsgel: function(){
return this.msgel || (this.msgel = document.getElementById(this.elid));
},
year: function(){return this.y = this.now.getFullYear();},
months: ['January','February','March','April','May','June','July','August','September','October','November','December'],
month: function(){return this.mnth = this.months[this.now.getMonth()];},
days: ['Sunday','Monday','Tuesday','Wednesday','Thursday','Friday','Saturday'],
day: function(){return this.d = this.days[this.now.getDay()];},
date : function(){return this.dt = this.now.getDate();},
hours: function(){return this.h = this.hrs = this.now.getHours();},
mins: function(){return this.m = this.mns = this.now.getMinutes();},
secs: function(){return this.s = this.scs = this.now.getSeconds();},
th: ['th', 'st', 'nd', 'rd'],
ampm: function(){
this.suffix = this.hrs > 11? 'PM' : 'AM';
this.h = this.hrs > 11? this.hrs - 12 : this.hrs;
if(this.h === 0){this.h = 12;}
this.m = this.mns > 9? this.mns : '0' + this.mns;
this.s = this.scs > 9? this.scs : '0' + this.scs;
this.dtth = this.dt + (this.th[this.dt] || this.th[this.dt - 30] || this.th[this.dt - 20] || 'th');
return this.suffix;
},
cycle: function(continueOn){
this.now = new Date();
this.year();
this.month();
this.day();
this.hours();
this.mins();
this.secs();
this.date();
this.ampm();
var r = -1, f = -1;
while(++f < this.fallbacks.length){
this.executerange.apply(this, [this.hrs, this.hrs + 1].concat(this.fallbacks[f]));
}
while(++r < this.ranges.length){
this.executerange.apply(this, this.ranges[r]);
}
if(continueOn === false){return;}
var inst = this;
this.repeat = setInterval(function(){inst.cycle(false);}, 1000);
},
init: function(){
return this;
},
ranges: [],
fallbacks: []
};
</script>
</head>
<body>
<div id="timemsg"></div>
<script type="text/javascript">
var mytime = timedriver.init();
mytime.elid = 'timemsg';
mytime.fallback(["Hello! It's<br>"], function(){document.body.style.background = 'lightyellow';});
mytime.setrange('0', '8', ["Good Morning! It's<br>", ", Up early, huh?"], function(){document.body.style.background = 'yellow';});
mytime.setrange('18', '20', ["Good Evening! It's<br>", ", Nice evening, huh?"], function(){document.body.style.background = 'pink';});
mytime.setrange('20', '21', ["Good Evening! It's<br>", ", Nice night, huh?"], function(){document.body.style.background = 'lightblue';});
mytime.setrange('22', '23:59', ["Good Night! It's<br>", ", Why are you still up?"], function(){document.body.style.background = 'blue';});
mytime.setrange('12', '18:30', ["Good Afternoon! It's<br>", ", How's it going?"], function(){document.body.style.background = 'gray';});
mytime.cycle();
</script>
</body>
</html>

Any questions, just let me know.