Meteor redraw clock every second - meteor

Template.display_time.time = function() {
var date = new Date();
var hour = date.getHours();
var minute = date.getMinutes();
var now = addZero(hour) + ":" + addZero(minute);
return now
};
At the moment im using this code to display the time.
But I've been trying to use simple javascript to update it every second, yet it wont show up on the page.
Is there a meteor friendly way to do this using the function above?
Like using setTimeout on 1 second interval..
The javascript I used to use.
function updateTime() {
var currentTime = new Date();
var hours = currentTime.getHours();
var minutes = currentTime.getMinutes();
if (hours < 10)
{
hours = "0" + hours;
}
if (minutes < 10)
{
minutes = "0" + minutes;
}
var v = hours + ":" + minutes + " ";
setTimeout("updateTime()",1000);
document.getElementById('time').innerHTML=v;
}
updateTime();

The reason that method doesn't work is because it isn't a reactive data source.
Try the following.
Template.display_time.time = function() {
return Session.get('time');
};
Meteor.setInterval(function() {
Session.set('time', getTime());
}, 1000);
See the documentation on Deps
"Meteor has a simple dependency tracking system which allows it to
automatically rerun templates and other computations whenever Session
variables, database queries, and other data sources change."

Related

How to fix Google Apps Script for local time and automatically clear a cell

I am creating a shared agenda that has to be filled by different people. Everytime they modify a certain cell, the date of change (day) is reported in another cell on the same row. The code below is currently working, but there are 3 minor problems:
The local time is not correct (I am living in italy)
I would like to see the time as well (hours:minutes)
If the modified cell is cleared (like if the text is deleted), also the date of change should disappear.
I find this type of code difficult to debug and would appreciate any help.
Thank you in advance,
function onEdit(event) {
var cell = event.source.getActiveCell();
var sheet = cell.getSheet();
var headers= sheet.getDataRange().getValues()[0];
var statusCol = headers.indexOf('Status') + 1 ;
var ss = event.source.getActiveSheet();
if (event.range.columnStart != 2) {
} else {
ss.getRange(event.range.rowStart, 5)
.setValue(getDate(new Date()));
}
var tt = event.source.getActiveSheet();
if (event.range.columnStart != 34) {
return;
} else {
tt.getRange(event.range.rowStart, 37)
.setValue(getDate(new Date()));
}
}
function getDate(d) {
if (d) {
return d.getDate() + "/" + (d.getMonth()+1) + "/" + d.getYear();
}
}
Add TimeZone, Hours, Minutes and deletes Datetime if cell contents is deleted.
It adds hours and minutes in 24 hour format with a timezone correction and if e.value is null then it deletes the contents of the datetime cell.
function onEdit(e) {
var ss=e.source;
var rg=e.range;
var sh=rg.getSheet();
if(rg.columnStart!=2 && rg.columnStart!=34){return;}
if(rg.columnStart==2){
if(e.value) {
sh.getRange(rg.rowStart, 5).setValue(Utilities.formatDate(new Date(new Date().getFullYear(),new Date().getMonth()+1,new Date().getDate(),new Date().getHours(),new Date().getMinutes()),Session.getScriptTimeZone(),"d/MMM/yyyy HH:mm"));
}else{
sh.getRange(rg.rowStart, 5).setValue('');
}
}
if (rg.columnStart==34) {
if(e.value) {
sh.getRange(rg.rowStart, 37).setValue(Utilities.formatDate(new Date(new Date().getFullYear(),new Date().getMonth()+1,new Date().getDate(),new Date().getHours(),new Date().getMinutes()),Session.getScriptTimeZone(),"d/MMM/yyyy HH:mm"));
}else{
sh.getRange(rg.rowStart, 37).setValue('');
}
}
}
Spreadsheet Edit Event Object
Utilities.formatDate()

Can't access meteor lib helpers from client

I'm trying to understand meteorjs and have a little question.
I wanted to create a getDateTime helper and wanted this helper to be available on the client and the server.
I then inserted this code in lib/helpers
function getDateTime() {
var now = new Date();
var year = now.getFullYear();
var month = now.getMonth()+1;
var day = now.getDate();
var hour = now.getHours();
var minute = now.getMinutes();
var second = now.getSeconds();
if(month.toString().length == 1) {
var month = '0'+month;
}
if(day.toString().length == 1) {
var day = '0'+day;
}
if(hour.toString().length == 1) {
var hour = '0'+hour;
}
if(minute.toString().length == 1) {
var minute = '0'+minute;
}
if(second.toString().length == 1) {
var second = '0'+second;
}
var dateTime = year+'/'+month+'/'+day+' '+hour+':'+minute+':'+second;
return dateTime;
}
Unfortunately this function is not available ( "undefined" ) on the client.
When I look at the source, I can see it but it is encapsulated in:
(function(){ };
I don't quite understand why this is for.
What should I do to access the function?
Each .js file in a Meteor application is enclosed in an immediately-invoked function expression (function () { ... })() to prevent local variables from cluttering the global scope. To make that function accessible in other files, define it like this:
// note: no "var"
getDateTime = function () {
// ...
};

Flex 4 utc date time format problem

here are my functions they work fine when timeoffset is round number(1,2,3,4...),but when is 3.5(3:30), 4.5(4:30) it doesnt work.
Can someone help me with this :
private function init_vars():void
{
timeZoneOffset = FlexGlobals.topLevelApplication.parameters.clock_time_zone; // I load this with js
timeZoneOffset = 5,50; // just for test
}
private function tick(event:TimerEvent):void
{
var local: Date = new Date();
var utc: Date = new Date(local.getTime() + (local.getTimezoneOffset() * 60000));
var utcTime:Number=utc.getTime();
var new_offset_date:Number = utcTime + ((3600000) * timeZoneOffset);
var new_date:Date = new Date(new_offset_date);
currentTime = new Date(new_date);
showTime(currentTime); // another function just to display time
}
private function showTime(time:Date):void
{
seconds = time.getSeconds();
minutes= time.getMinutes();
hours= time.getHours();
//rotate
this.secondsPointer.rotation = (seconds * 6) - 90;
this.minutesPointer.rotation = (minutes * 6) - 90;
this.hoursPointer.rotation = (hours * 30) + (minutes * 0.5) - 90;
this.secondsPointer.visible = true;
this.minutesPointer.visible = true;
this.hoursPointer.visible = true;
}
I ran your code and it worked fine. I just traced currentTime because I didn't have your showTime function, is it possible that the bug is in that function?
I would recommend to try something like the following if you can:
date.setUTCHours(date.getUTCHours() + hoursDifference); //5
date.setUTCMinutes(date.getUTCMinutes + minutesDifference); //30
Modifying dates using the time in milliseconds, depending on how/where/when you actually use the application might create weird bugs in case of daylight savings. And you don't want to deal with a bug that might happen only twice a year in only certain countries of the world.

flex countdown algorithm

The algorithm must take in an Int-value of the number of seconds remaining (ex. 2005), then convert and return a "0-padded-String" of the hours, minutes, and seconds remaining (ex. 02:35:15).
I have another event handler that will invoke the above algorithm change in seconds (count down).
Here is an implementation for your conversion method:
public static function Seconds2HHMMSS(Time:Number):String
{
var hours:int =int(int(Time/60)/60);
var hoursZeroPadding:String = "";
if (hours<10)
hoursZeroPadding="0";
var minutes:int =int(Time/60)%60;
var minutesZeroPadding:String = "";
if (minutes<10)
minutesZeroPadding="0";
var seconds:int =Time%60;
var secondsZeroPadding:String = "";
if (seconds<10)
secondsZeroPadding="0";
var result:String = hoursZeroPadding + hours.toString()
+ minutesZeroPadding + minutes.toString()
+ secondsZeroPadding + seconds.toString();
return result;
}
The opposite conversion is quite simpler:
public static function HHMMSS2Seconds(Time:String):int
{
var result:int = int(Time.substr(0,2))*3600
+ int(Time.substr(2,2))*60
+ int(Time.substr(4,2));
return result;
}
Use div and mod and your knowledge of how many seconds in an hour / min / second to come up with each of the groupings. You can then do a padding of zeros with an if statement (or the ?: operator)
Edit: or just use Dunaril's code, I didn't want to just give you the code without you having tried something first, that goes against the spirit of SO for me :P

Is there a JQuery plugin to convert UTC datetimes to local user timezone?

If I have a tag:
<span class="utctime">2010-01-01 11:30 PM</span>
I would like a jquery script or plug in to convert every utctime class to the current user's browser local time. I would prefer to find this before writing one.
Ok, so I created one that does it:
/*
Note: this requires that the JQuery-DateFormat plugin (available here) be loaded first
http://plugins.jquery.com/project/jquery-dateFormat
*/
(function ($) {
$.fn.localTimeFromUTC = function (format) {
return this.each(function () {
// get time offset from browser
var currentDate = new Date();
var offset = -(currentDate.getTimezoneOffset() / 60);
// get provided date
var tagText = $(this).html();
var givenDate = new Date(tagText);
// apply offset
var hours = givenDate.getHours();
hours += offset;
givenDate.setHours(hours);
// format the date
var localDateString = $.format.date(givenDate, format);
$(this).html(localDateString);
});
};
})(jQuery);
Usage:
<span class="utcdate">2/5/2010 10:30 PM</span>
$('.utcdate').localTimeFromUTC('MM/dd/yyyy hh:mm a');
Use input date to find time zone offset. Important for DST changes.
(function ($) {
$.fn.localTimeFromUTC = function (format) {
return this.each(function () {
// get provided date
var tagText = $(this).html();
var givenDate = new Date(tagText);
if(givenDate == 'NaN') return;
// get time offset from browser
var offset = -(givenDate.getTimezoneOffset() / 60);
// apply offset
var hours = givenDate.getHours();
hours += offset;
givenDate.setHours(hours);
// format the date
var localDateString = $.format.date(givenDate, format);
$(this).html(localDateString);
});
};
})(jQuery);
Use it like....
function ConvertDatesToLocalTime() {
$('.ConvertUtcToLocal').localTimeFromUTC('MM/dd/yyyy hh:mm:ss a');
}
$(document).ready(function () {
ConvertDatesToLocalTime();
});
Assign 'ConvertUtcToLocal' class to all elements requiring conversion.
$(".localdatetime").each(function () {
var datestr = $(this).text();
//alert(datestr);
if (datestr.trim() != '') {
var dateOb = (new Date(Date.parse(datestr, 'MM-dd-yyyy HH:mm'))).setTimezone("GMT").toString('dd MMM yyyy hh:mm tt');
//alert(dateOb);
$(this).text(dateOb);
}
})
this can also be used along with Date.js library to display time in user timezone
CodeGrue thanks so much for sharing this with the community.
For those who are forced to work with other timezones than UTC .. you can alter the function by adding the time difference like this:
Original snippet:
var offset = -(currentDate.getTimezoneOffset() / 60);
Snippet altered to work with CEST timezone (Time zone offset: UTC + 2 hours):
var offset = -(currentDate.getTimezoneOffset() / 60 + 2);
and so on.
When I used this, I had to change the line
var hours = givenDate.getHours();
to
var hours = givenDate.getUTCHours();
When debugging through this, the line var givenDate = new Date(tagText) ends up creating a Date object that is in UTC (if you give it a date in RFC1123 format, e.g. ddd, dd MMM yyyy HH:mm:ss GMT), but when you call getHours on that you get the hours in the local time zone. So unless you call getUTCHours, it doesn't work.
So the full thing is
/*
Note: this requires that the JQuery-DateFormat plugin be loaded first
http://plugins.jquery.com/project/jquery-dateFormat
*/
(function ($) {
$.fn.localTimeFromUTC = function (format) {
return this.each(function () {
// get time offset from browser
var currentDate = new Date();
var offset = -(currentDate.getTimezoneOffset() / 60);
// get provided date
var tagText = $(this).html();
var givenDate = new Date(tagText);
// apply offset
var hours = givenDate.getUTCHours();
hours += offset;
givenDate.setHours(hours);
// format the date
var localDateString = $.format.date(givenDate, format);
$(this).html(localDateString);
});
};
})(jQuery);
See this other question for how I used it in combination with the timeago plugin.

Resources