Flex 4 utc date time format problem - apache-flex

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.

Related

Meteor redraw clock every second

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."

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

Playing sound files one after another in flex AIR code

I have a set of sound clips to be played one after another in a sequence with couple of time interval inbetween.
In my case, its a question - followed by the set of four options.
When I write the below code, all the audop files start together at same time. How can I had time delay inbetween, so that the second clip plays only after the first one is over, and the third one starts playing, only when the second option is over.
I am with Flex AIR AS 3. See code below. Thanks in advance.
private function playCoundClips(): void
{
//set audio clips
var questionClipSource : String = "assets/quiz_voiceovers/" + questionCode + "Q.mp3";
var optionAClipSource : String = "assets/quiz_voiceovers/" + questionCode + "a.mp3";
var optionBClipSource : String = "assets/quiz_voiceovers/" + questionCode + "b.mp3";
var optionCClipSource : String = "assets/quiz_voiceovers/" + questionCode + "c.mp3";
var optionDClipSource : String = "assets/quiz_voiceovers/" + questionCode + "d.mp3";
playThisClip(questionClipSource);
playThisClip(optionAClipSource);
playThisClip(optionBClipSource);
playThisClip(optionCClipSource);
playThisClip(optionDClipSource);
}
private function playThisClip(clipPath : String) : void
{
try
{
clipPlayingNow = true;
var soundReq:URLRequest = new URLRequest(clipPath);
var sound:Sound = new Sound();
var soundControl:SoundChannel = new SoundChannel();
sound.load(soundReq);
soundControl = sound.play(0, 0);
}
catch(err: Error)
{
Alert.show(err.getStackTrace());
}
}
Thanks
Sumit
The problem is you are spawning multiple asynchronous calls. Implement a complete call back function on Sound and then call your playThisClip function inside the callback function. (You can sleep for predefined time before calling)
Time delay, is a very bad idea (in 99% of the case).
Have a look at the SOUND_COMPLETE event (see the doc)
This event is triggered when the sound stops playing.
So, it's now very easy to play sounds in sequence.
A simple example (not tested but idea is here) :
//declare somewhere a list of sounds to play
var sounds:Array=["sound_a.mp3","sound_a.mp3"];//sounds paths
//this function will play all sounds in the sounds parameter
function playSounds(sounds:Array):void{
if(!sounds || sounds.length==0){
//no more sound to play
//you could dispatch an event here
return;
}
var sound:Sound=new Sound();
sound.load(new URLRequest(sounds.pop()));
var soundChannel:SoundChannel = sound.play();
soundChannel.addEVentListener(Event.SOUND_COMPLETE,function():void{
soundChannel.removeEventListener(Event.SOUND_COMPLETE,arguments.callee);
playSounds(sounds);
});
}
This helped me
http://livedocs.adobe.com/flex/3/html/help.html?content=Working_with_Sound_09.html
One need to write code for:
sound.addEventListener(Event.ENTER_FRAME, onEnterFrame);
soundControl.addEventListener(Event.SOUND_COMPLETE, onPlaybackComplete);
private function onEnterFrame(event:Event):void
{
var estimatedLength:int =
Math.ceil(sound.length / (sound.bytesLoaded / sound.bytesTotal));
var playbackPercent:uint =
Math.round(100 * (soundControl.position / estimatedLength));
}
private function onPlaybackComplete(event:Event):void
{
Alert.show("Hello!");
}

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.

Programmatically Mixdown of audio tracks (no playback)

I've found some excellent demos of how to mix together sound objects together for live playback. See the working example bellow...
But can it be done programmatically without any playback so I can just output the mixed file? Also I'll be adding some volume change info along the way so it'll need to be added in small chunks like how the play buffer works.
[Embed(source = "audio/track01.mp3")]
private var Track1:Class;
[Embed(source = "audio/track02.mp3")]
private var Track2:Class;
[Embed(source = "audio/track03.mp3")]
private var Track3:Class;
[Embed(source = "audio/track04.mp3")]
private var Track4:Class;[Embed(source = "AudioMixerFilter2.pbj",mimeType = "application/octet-stream")]
private var EmbedShader:Class;
private var shader:Shader = new Shader(new EmbedShader());
private var sound:Vector.<Sound> = new Vector.<Sound>();
private var bytes:Vector.<ByteArray> = new Vector.<ByteArray>();
private var sliders:Vector.<Number> = new Vector.<Number>();
private var sliderVol:int = 1;
private var BUFFER_SIZE:int = 0x800;
public var playback:Sound = new Sound();
public function startAudioMixer(event:FlexEvent):void{
sound.push(new Track1(), new Track2(), new Track3(), new Track4());
sliders.push(sliderVol,sliderVol,sliderVol,sliderVol);
playback.addEventListener(SampleDataEvent.SAMPLE_DATA, onSoundData);
playback.play();
}
private function onSoundData(event:SampleDataEvent):void {
for(var i:int = 0; i < sound.length; i++){
bytes[i] = new ByteArray();
bytes[i].length = BUFFER_SIZE * 4 * 2;
sound[i].extract(bytes[i], BUFFER_SIZE);
var volume:Number = 0;
bytes[i].position = 0;
for(var j:int = 0; j < BUFFER_SIZE; j++){
volume += Math.abs(bytes[i].readFloat());
volume += Math.abs(bytes[i].readFloat());
}
volume = (volume / (BUFFER_SIZE * .5)) * sliderVol; // SLIDER VOL WILL CHANGE
shader.data['track' + (i + 1)].width = BUFFER_SIZE / 1024;
shader.data['track' + (i + 1)].height = 512;
shader.data['track' + (i + 1)].input = bytes[i];
shader.data['vol' + (i + 1)].value = [sliders[i]];
}
var shaderJob:ShaderJob = new ShaderJob(shader,event.data,BUFFER_SIZE / 1024,512);
shaderJob.start(true);
}
Easiest way would be to just forget about the Pixel Bender stuff.
Once the Sounds are loaded, use an ENTER_FRAME that uses Sound.extract to get a smallish ByteArray from each Sound, then read through all four extracted ByteArrays doing some basic math to arrive at the 'mixed' values for the left & right signals. Write those values to the "final/mixed/output" ByteArray. Repeat the process each frame until you're at the end of the sounds. If the Sounds aren't all the identical length, you'll need to figure out how to handle that as well.
If you need to perform a mix where the amplitude of each track changes over time, it'd be a good challenge, but would take time to set up.
While you're at it, check out Andre Michelle's Tonfall project... It's a complex but great place to start with understanding the ins/outs of audio in AS3.

Resources