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>
Related
//<![CDATA[
var displayCurrentTime = new function() {
// Get values...
var sysHour = getHours(); // Get Hours
var curHour = 0; // Initialize current hour (12 hr format)
var morningEvening = "AM"; // Initialize AM/PM notation
if (sysHour < 13) { // If it's in the morning, set time as is.
curHour = sysHour;
morningEvening = "AM"
} else {
curHour = sysHour - 12; // If it's in the evening, subtract 12 from the value and use "PM"
morningEvening = "PM"
}
var curMins: getMinutes; // Get current minutes...
// Capture the ID of the notification bar div, and compose a string from the above values.
var notificationBar = document.getElementById("notificationBar");
var dateTimeString = curHour + ":" + curMins + " " + morningEvening;
// All that code above files into this fun stuff.
notificationBar.innerHTML = dateTimeString;
}
window.setInterval(function() {
displayCurrentTime();
}, 1000);
//]]>
I've been reading up some information and I wanted to create a simple script that grabs the hour and minute, does some calculations to determine if it's AM or PM, creates a string variable from those results, and then slips it inside of a specific DIV element. It does this every second.
Most of the code I've written seems to make sense based on what I've read. In the beginning I've tried using function displayCurrentTime() {} as well as what you see below (var displayCurrentTime = new function() {}) and neither seem to work. I cannot get my text to display in the page. Note: the ID of the div is notificationBar, just as it is here.
Is there anything in this code that makes no sense, or does this actually warrant posting the full HTML?
You don't need new in front of function that you newly define, you don't instantiate class.
You have few syntax errors, like var curMins : ... instead of var curMins = ....
Also, you cannot use getHours() and getMinutes() methods, outside of Date object:
var displayCurrentTime = function() {
// Get values...
var d = new Date();
var sysHour = d.getHours(); // Get Hours
var curHour = 0; // Initialize current hour (12 hr format)
var morningEvening = "AM"; // Initialize AM/PM notation
if (sysHour < 13) { // If it's in the morning, set time as is.
curHour = sysHour;
morningEvening = "AM"
} else {
curHour = sysHour - 12; // If it's in the evening, subtract 12 from the value and use "PM"
morningEvening = "PM"
}
var curMins = d.getMinutes(); // Get current minutes...
var curSecs = d.getSeconds(); //optionally get seconds too
// Capture the ID of the notification bar div, and compose a string from the above values.
var notificationBar = document.getElementById("notificationBar");
var dateTimeString = curHour + ":" + curMins + ":" + curSecs + " " + morningEvening;
// All that code above files into this fun stuff.
notificationBar.innerHTML = dateTimeString;
}
window.setInterval(function(){ displayCurrentTime(); }, 1000);
<div id='notificationBar'>
Time Here
</div>
See about Date object:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date
About functions and anonymous function expression:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions#The_function_expression_(function_expression)
Also:
https://developer.mozilla.org/en-US/docs/Learn/JavaScript/Howto
There are a few syntax errors in your function, I'll get to them one by one:
You shouldn't use new when declaring a function. Just drop it =) var displayCurrentTime = function() {
You are trying to assign a value to a variable using json syntax : in var minutes: getMinutes. You also forgot to execute the function, so try var minutes = getMinutes();
In (2) I assume you already declared the methods getHours and getMinutes, but if not, you can call them directly from a new Date object:
var date = new Date();
var sysHours = date.getHours();
var minutes = date.getMinutes();
//...
That should do it!
Extra: you can skip adding the displayCurrentTime to another function inside the setInterval function: window.setInterval(displayCurrentTime, 1000);
var displayCurrentTime = function() {
var date = new Date(); // Get current date object
var sysHour = date.getHours(); // Get Hours
var curHour = 0; // Initialize current hour (12 hr format)
var morningEvening; // No need to initialize
if (sysHour < 13) { // If it's in the morning, set time as is.
curHour = sysHour;
morningEvening = "AM"
} else {
curHour = sysHour - 12; // If it's in the evening, subtract 12 from the value and use "PM"
morningEvening = "PM"
}
var curMins = date.getMinutes(); // Get Minutes
// Capture the ID of the notification bar div, and compose a string from the above values.
var notificationBar = document.getElementById("notificationBar");
var dateTimeString = curHour + ":" + curMins + " " + morningEvening;
// All that code above files into this fun stuff.
notificationBar.innerHTML = dateTimeString;
}
window.setInterval(displayCurrentTime, 1000);
<div id='notificationBar'></div>
i'm trying to display a difference between dates using moment.js and update it every second. More specificly my age.
I'm using moment.js and a plugin called moment-precise-range.js
I get the difference correctly:
function fecha() {
var m1 = moment('1989-11-29 04:00:00','YYYY-MM-DD HH:mm:ss');
var m2 = moment(moment(),'YYYY-MM-DD HH:mm:ss');
var diff = moment.preciseDiff(m1, m2);
document.write(diff)
}
fecha()
And then, I'm trying to use SetInterval():
var myVar = setInterval(myTimer, 1000);
function myTimer() {
var m1 = moment('1989-11-29 04:00:00','YYYY-MM-DD HH:mm:ss');
var m2 = moment(moment(),'YYYY-MM-DD HH:mm:ss');
var diff = moment.preciseDiff(m1, m2);
document.write(diff)
}
But it doesn't work. (I think it keeps loading the webpage but not sure)
What am I doing wrong? Thanks.
It seems like your code is crashing at
moment.preciseDiff(m1,m2);
Here's a working sample of your code with the regular moment.diff()
$(document).ready(function() {
var myVar = setInterval(myTimer, 1000);
function myTimer() {
var m1 = moment('1989-11-29 04:00:00','YYYY-MM-DD HH:mm:ss');
var m2 = moment(moment(),'YYYY-MM-DD HH:mm:ss');
document.write(m2.diff(m1) + "\n");
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.17.1/moment.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
I'm trying to create a timer from when the user clicks a button.
To do this I tried to calculate the difference between two date objects. When I output the difference, it works. However thetoLocaleTimeString call returns a string with an extra hour added:
var start;
var timer;
function myTimer() {
var current = new Date();
var difference = new Date(current - start);
console.log(difference.getTime(), difference.toLocaleTimeString(navigator.language));
document.getElementById("timer").innerHTML = difference;
document.getElementById("timer2").innerHTML = difference.toLocaleTimeString('en-GB');
}
start = new Date();
timer = setInterval(myTimer, 1000);
draw();
<h1 id="timer"></h1>
<h1 id="timer2"></h1>
What am I doing wrong?
Specify the time zone as UTC in the options argument. Otherwise, the difference date will be adjusted to the user agent's time zone.
document.getElementById("timer2").innerHTML = difference.toLocaleTimeString('en-GB', { timeZone: 'UTC' });
Read more on the options argument and toLocaleTimeString in the MDN documentation.
var start;
var timer;
function myTimer() {
var current = new Date();
var difference = new Date(current - start);
console.log(difference.getTime(), difference.toLocaleTimeString(navigator.language));
document.getElementById("timer").innerHTML = difference;
document.getElementById("timer2").innerHTML = difference.toLocaleTimeString(navigator.language, { timeZone: 'UTC', hour12: false });
}
start = new Date();
timer = setInterval(myTimer, 1000);
draw();
<h1 id="timer"></h1>
<h1 id="timer2"></h1>
Because of the problems with JS and timezones, you are better of using something like moment.js's timezone (http://momentjs.com/timezone/) to do correct conversions (that keep in mind the shift of BST, GMT, differences between countries, etc..). For the purpose of your timer, the following would work as well, and is more accurate as well as simpler to reason about:
// Use Date.now() to get the time in milliseconds for this local computer
var start = Date.now();
var time = new Date();
// This function will prepend a 0 to a number lower than 10
function prependZero(v){
if(v < 9) return '0' + v;
else return v;
}
var timer = setInterval(function() {
// Calculate the difference using the computers local time strings
var difference = new Date(Date.now() - start);
document.getElementById("timer").innerHTML = new Date();
// Now use the Date mnethods to get the correct output:
document.getElementById("timer2").innerHTML = prependZero(difference.getHours()) + ':' + prependZero(difference.getMinutes()) + ':' + prependZero(difference.getSeconds());
}, 1000);
<h1 id="timer"></h1>
<h1 id="timer2"></h1>
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;
}
}
I have a url that change every day based on today's date, for example:
http://www.newspaper.com/edition/20141227.html
where 20141227 is in the format YYYYMMDD.
Can I include the date using JavaScript? If possible, how would I do that?
I think following steps will help you to achieve the functionality your are looking for
1.Convert the today's date or any date to intended format that is "YYYYMMDD" in your case.
2.Then append it to your URL.
Please look into code snippet for details. Note you just need to hover over URL to know what it is pointing to.
Date.prototype.toMyString = function () {
//If month/day is single digit value add perfix as 0
function AddZero(obj) {
obj = obj + '';
if (obj.length == 1)
obj = "0" + obj
return obj;
}
var output = "";
output += this.getFullYear();
output += AddZero(this.getMonth()+1);
output += AddZero(this.getDate());
return output;
}
var d = new Date();
var link = document.getElementById("link");
link.setAttribute("href","/yourchoiceofURL?t="+d.toMyString());
<ul>
<li><a id="link" href="#">Any URL</a></li>
</ul>
var date = new Date().toDateString("yyyyMMdd");
then paste the date in building the URL
url = "http://blahblahblaj.com/"+date
You can try the below code. Hope this helps.
var today = new Date();
var dd = today.getDate();
var mm = today.getMonth()+1; //January is 0!
var yyyy = today.getFullYear();
if(dd<10){dd='0'+dd};
if(mm<10){mm='0'+mm};
today = yyyy+mm+dd;
var new_url=document.URL+"/"+today+".html";
console.log(new_url);
Here's a simpler method that works
<script>
var link = document.getElementById('link'); // ref. to your anchor tag
var d = new Date,
date = d.getDate(),
month = d.getMonth()+1, // Months in JavaScript are 0 indexed
year = d.getFullYear();
if(date < 10) date = ("0" + date);
if(month < 10) month = ("0" + month);
link.href = ("STATIC_URL/" + year + month + date);//Concatenating three numbers, kind of a hack
</script>
This is as simple as it gets.
Thanks for all the answers colleagues. For Dnyanesh, I tried the code in http://jsfiddle.net/ can work well. I try to enter into an html page like this, why can not run perfectly. Where is the mistake?
<html>
<head>
<script type='text/javascript'>
Date.prototype.toMyString = function () {
//If month/day is single digit value add perfix as 0
function AddZero(obj) {
obj = obj + '';
if (obj.length == 1)
obj = "0" + obj
return obj;
}
var output = "";
output += this.getFullYear();
output += AddZero(this.getMonth()+1);
output += AddZero(this.getDate());
return output;
}
var d = new Date();
var link = document.getElementById("link");
link.setAttribute("href","http://www.pressdisplay.com/pressdisplay/pageview.aspx?issue=1245"+d.toMyString()+"00000000001001");
</script>
</head>
<body>
<a id="link" href="#">Any URL</a>
</body>
</html>
Thank you for all, all of the recommended code runs fine. If you want to put into the HTML code , add the following code to be loaded in the browser :
//<![CDATA[
window.onload=function(){
....javascript code here....
}//]]>