how to display a string only during a specific time with javascript? - javascript

I am currently making a live banner for my school website. It should include the day of the week, the date, the time, and the current period number. I'm sorted with the first three but the last one gives me trouble as it needs to be displayed only during a 45 minute period of time.
I improved my code from yesterday. Now it looks like this (CODEPEN).
BTW, Thanks to all who have helped me yesterday too! Special thanks to theRoot, for making me have my code simple
<!-->
LIVE DATE AND DAY
<-->
<style>
BODY {
font-family: arial;
}
</style>
<body onload="startTime()">
<p>
<span style="font-size:40pt;">TODAY IS A
<script>
var today = new Date();
var dd = today.getDate();
var ww = today.getDay();
var mm = today.getMonth();
var yyyy = today.getFullYear();
var suffix = ["st","nd","rd","th"];
var op = "";
var month = ["JANUARY","FEBUARY","MARCH","APRIL","MAY","JUNE","JULY","AUGUST","SEPTEMBER","OCTOBER","NOVEMBER","DECEMBER"];
var day = ["MONDAY","TUESDAY","WEDNSDAY","THURSDAY","FRIDAY","SATURDAY","SUNDAY"];
if(parseInt(dd) > 4)
op+=" "+day[ww-1]+" THE "+dd+suffix[3].sup()+" OF ";
else
op+=" "+day[ww-1]+" THE "+dd+suffix[(parseInt(dd)%10)-1].sup()+" OF ";
op+=month[parseInt(mm)-1]+" "+yyyy;
document.write(op);
</script>
<script>
function startTime() {
var today=new Date();
var h=today.getHours();
var m=today.getMinutes();
m = checkTime(m);
var am = " am";
var pm = " pm";
if(h > 12) {
h =(h - 12)
document.getElementById('time').innerHTML = h+":"+m+pm.sup();
} else {
document.getElementById('time').innerHTML = h+":"+m+am.sup();
}
var t = setTimeout(function(){startTime()},500);
var period = ["WHY SO EARLY?","BEFORE SCHOOL","PERIOD 1","PERIOD 2","PERIOD 3","PERIOD 4","PERIOD 5","PERIOD 6","PERIOD 7","PERIOD 8","PERIOD 9","PERIOD 10","AFTER SCHOOL","WHY ARE STILL YOU HERE?",];
}
function checkTime(i) {
if (i<10) {i = "0" + i}; // add zero in front of numbers < 10
return i;
}
</script>
<p style="font-size:40pt; display:inline;" id="time"></p>
</span>
</p>
</body>
This is what I have as of now.
Thanks.

So you can have a reference about start time for each period and then map it accordingly with period array.Here is a updated fork http://codepen.io/anon/pen/eNVdRq
var per=h*60+m;
for(var i=0;i<ptime.length-1;i++){
if(per>ptime[i]&&per<ptime[i+1]){
document.getElementById('period').innerHTML=period[i];
break;
}
}

Related

Js moments timezone

I have the following code to manipulate the time in copenhagen. I was wondering how i would be able to implement this using js moment?
function startTime() {
var today=new Date();
var i=today.getHours();
var h = i-2;
var m=today.getMinutes();
var s=today.getSeconds();
m = checkTime(m);
s = checkTime(s);
document.getElementById('localtime').innerHTML = h+":"+m+":"+s;
var t = setTimeout(function(){startTime()},500);
}
function checkTime(i) {
if (i<10) {i = "0" + i}; // add zero in front of numbers < 10
return i;
}
<body onload="startTime()">
You'll need the timezone plugin if you want specific timezones. Otherwise you can leave it out. Provides .tz()
function startTime() {
//local time
document.getElementById('localtime').innerHTML =
moment().format('hh:mm:ss');
//copenhagen timezone
document.getElementById('copenhagen').innerHTML =
moment.tz('Europe/Copenhagen').format('hh:mm:ss');
var t = setTimeout(function(){startTime()},500);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.10.2/moment-with-locales.js"></script>
<script src="http://momentjs.com/downloads/moment-timezone-with-data.js"></script>
<body onload="startTime()">
<div id="localtime"></div>
<div id="copenhagen"></div>
</body>

How to get nth Weekday of Current date in javascript

I need to retrieve nth weekday of the current date in js. like 1st Sunday, 2nd Sunday
var d=new Date();
var weekDay=d.getDay();
here weekDay gives me 4 that means its Wednesday(3rd Wednesday). So far its good.
from weekDay i can say that its wednesday.
how to calcuate the "3rd" index of this wednesday?
Thank you
What du you actually mean? To get the dates you could use Date(). Like for instance creating a variable "today" and setting it to be todays date.
var today = new Date();
In a greater context you could go as far as showing everything from weekdays, date, year etc etc! I'll provide a code bit below. The code shows a dynamic clock/date in HTML.
You can format this the way you want, and choose which variables to show! This is btw the same code as found here: Other thread/question
<!DOCTYPE html>
<html>
<head>
<script>
function startTime() {
var today=new Date();
var day = today.getDate();
var month = today.getMonth();
var year = today.getFullYear();
var h=today.getHours();
var m=today.getMinutes();
var s=today.getSeconds();
m = checkTime(m);
s = checkTime(s);
document.getElementById('txt').innerHTML = "Date: " + day + "/" + month + "/" + year + " " + "Clock: " + h+":"+m+":"+s;
var t = setTimeout(function(){startTime()},500);
}
function checkTime(i) {
if (i<10) {i = "0" + i}; // add zero in front of numbers < 10
return i;
}
</script>
</head>
<body onload="startTime()">
<div id="txt"></div>
</body>
</html>
Is this what you mean?
Something like this
function getNth(dat) {
var days = ['sunday', 'monday', 'tuesday', 'wednesday', 'thursday', 'friday','saturday'],
nth = ['st', 'nd', 'rd', 'th', 'th'],
d = dat ? dat instanceof Date ? dat : new Date(dat) : new Date(),
date = d.getDate(),
day = d.getDay(),
n = Math.ceil(date / 7);
return n + nth[n-1] + ' ' + days[day];
}
document.body.innerHTML = '' +
'today ....: ' + getNth() + '<br>' +
'1/31/2015 : ' + getNth('1/31/2015') + '<br>' +
'1/16/2015 : ' + getNth('1/16/2015');
body {font-family: monospace}
As per my understanding you want what date will be 1st, 2nd sunday/Monday from today. If it is that then you can use this
//consider sun=o,mon=1,....,sat:6
function getWeekday(n,day)
{
var today = new Date();
var presentDay = today.getDay();
var presentTime = today.getTime();
if(day < presentDay)
{
day = day +6;
}
var diff = day - present day;
var daysAfter = (n-1)*7 + diff;
var timeAfter = presentTime+daysAfter*86400000;
var next date = new Date(timeAfter);
}
// if you want to get 1st sunday from today just call this
var sunday1 = getWeekday(1,0)
// to get second monday from today
var monday2 = getWeekday(2,1)

JavaScript : displaying Yesterdays Date in JavaScript

I was trying to display Yesterday Date on click of the button , but why its showing Date as "2013-6-0"
instead of 2013-05-31
Could anybody please tell me what i was doing wrong
<!DOCTYPE html>
<html>
<head>
<script>
function displayDate()
{
var d = new Date();
var curr_date = d.getDate()-1;
var curr_month = d.getMonth() + 1;
var curr_year = d.getFullYear();
var yesterday = curr_year + "-" + curr_month + "-" + curr_date ;
document.write(yesterday);
}
</script>
</head>
<body>
<p id="demo">Click Button to Display Yesterday Date</p>
<button type="button" onclick="displayDate()">Display Date</button>
</body>
</html>
You should update and then reference the date from which you've subtracted 1 day:
var d = new Date();
d.setDate(d.getDate() - 1); // <-- add this to make it "yesterday"
var curr_date = d.getDate(); // <-- don't subtract 1 anymore
var curr_month = d.getMonth() + 1;
var curr_year = d.getFullYear();
DEMO
Your code simply takes a day number (like 1, 2, ...) and subtracts one from it. Why would you expect that to automatically roll the day back to the previous month?
You can generate new dates by subtracting milliseconds from a given date. Try this:
var today = new Date();
# subtract milliseconds representing one day from current date
var yesterday = new Date(today - 24*60*60*1000);
var today = new Date();
var yesterday = new Date();
yesterday.setDate(today.getDate()-1);
var yesterdayStr = yesterday.getFullYear() + "-" + (yesterday.getMonth()+1) + "-" + yesterday.getDate();
function displayDate()
{
var today = new Date();
today.setDate(today.getDate()-1);
var yyyy = today.getFullYear().toString();
var mm = (today.getMonth()+1).toString();
mm = mm.length==2?mm:"0"+mm;
var dd = today.getDate().toString();
dd = dd.length==2?dd:"0"+dd;
var yesterday = yyyy+"-"+mm+"-"+dd;
document.write(yesterday);
}

Set new date 12 months after in a form

I am very new to script and checked many answers but could not find the complete answer.
In a form, I have a start date, number of months and end date - I want to display the end date when the start date is entered - I have created this script but I must be missing something.
Here's my code:
[script type="text/javascript" src=Datejs][/js]
[script type="text/javascript" ]
window.onload = function() {
var startdateEl = document.getElementById("customFields_cf_232");
var leasetermEl = document.getElementById("customFields_cf_34");
var enddateEl = document.getElementById("customFields_cf_38");
function CalculateDate {
var enddateEl=leasetermEl.months().startdateEl;
}
var enddateEl.onblur = CalculateDate;
};
[/script]
I made this. It listens to your keystrokes live. http://jsfiddle.net/4t54J/
<input name="startDate" type="text" value="MM-DD-YYYY" />
<input name="endDate" type="text" />
var SECOND = 1000;
var MINUTE = SECOND * 60;
var HOUR = MINUTE * 60;
var DAY = HOUR * 24;
var YEAR = DAY * 365.25;
var startDateInput = 'input[name="startDate"]';
var endDateInput = 'input[name="endDate"]';
$(startDateInput).live('keypress', function (e) {
var startDate = $(startDateInput).val();
var endDate = setEndDate(startDate);
$(endDateInput).val(endDate);
});
function setEndDate(startDate) {
var date = new Date();
var parts = startDate.split('-');
if (date != '' && parts.length > 2) {
// year, month (0-based), day
date.setFullYear(parts[2], parts[0] - 1, parts[1]);
date.setTime(date.getTime() + YEAR);
var mm = date.getMonth() + 1;
mm = (mm < 10 ? '0' : '') + mm.toString();
var dd = date.getDate();
var yyyy = date.getFullYear();
return mm + "-" + dd + "-" + yyyy;
} else {
return '';
}
}

How do I change a picture during the weekends with javascript?

I want to show on our site when the chat is available. The problem is that it won't be open in the weekends. How do I exclude them? Can it be done?
<html>
<body>
<script type="text/javascript">
function chatonoff(){
var now = new Date();
var hour = now.getHours();
if (hour >=9 && hour <=18)
{
document.getElementById("chat").src = "/bilder/butik/chat-open.png";
}
}
</script>
<img id="chat" src="/bilder/butik/chat.png" onload="chatonoff()">
</body>
</html>
You could do like this
function chatonoff(){
var now = new Date();
var hour = now.getHours();
var day = now.getDay();
//Check if weekend : in this case, I assume that saturday == 6 and Sunday = 0
//It depends on your location / timezone
if(day != 6 && day != 0)
{
if (hour >=9 && hour <=18)
{
document.getElementById("chat").src = "/bilder/butik/chat-open.png";
}
}
}
EDIT
About excluding hollidays :
You should create an array with all the off dates. Then, check if the curent day is present in the array
var offDaysListArray = ['2013-01-01','2013-01-02'];
var now = new Date();
var y = now .getFullYear();
var d = (now .getDate() < 10) ? '0'+now .getDate() : now .getDate();
var m = ((now .getMonth()+1) < 10) ? '0'+(now .getMonth()+1) : (now .getMonth()+1);
//Check if it is a closed day
if(offDaysListArray.indexOf(y + '-' + m + '-' + d) != -1)
return false; //It is a close day
Be carefull with indexOf, old browser like IE8 doesn't implement this function. Check Why doesn't indexOf work on an array IE8?
This is a very simple answer, although it won't exactly work as you want it to as JavaScript is run on the client side.
This means that someone on the other side of the world will be able to see your chat on HIS FRIDAY even though it is a SATURDAY for YOU (A Sunday/Monday example also works here). Ideally you would solve this by using some server side language such as Java / .NET / PHP or whatever you are using.
Here is your quick JavaScript fix:
<html>
<body>
<script type="text/javascript">
function chatonoff(){
var now = new Date();
var hour = now.getHours();
var day = now.getDay();
if (hour >=9 && hour <=18 && day >= 1 && day <= 5)
{
document.getElementById("chat").src = "/bilder/butik/chat-open.png";
}
}
</script>
<img id="chat" src="/bilder/butik/chat.png" onload="chatonoff()">
</body>
</html>

Categories

Resources