How to convert this JavaScript to C#?
<script>
function zeroPad(num, places) {
var zero = places - num.toString().length + 1;
return Array(+(zero > 0 && zero)).join("0") + num;
}
var accum = 0;
var pin = parseInt(form.mac.value.replace(/:/g, '').slice(-6), 16) % 12000;
var p = pin;
while (pin)
accum = (((accum + (3 * (pin % 10))) | 0) + (((pin / 10) | 0) % 10)) | 0, pin = ((pin / 100) | 0);
accum = ((10 - accum % 10) % 10);
form.pin.value = (zeroPad(p, 7) + "" + accum);
}
</script>
Please explain me this line in details?
parseInt(form.mac.value.replace(/:/g, '').slice(-6), 16) % 12000;
I believe start-to-finish code conversions are a bit out of scope of Stack Overflow. If you posted your non-working C# conversion attempt and asked where it went wrong, I'm sure you'd get a much quicker answer to your first question.
As for your second question:
parseInt(form.mac.value.replace(/:/g, '').slice(-6), 16) % 12000;
translates to:
// Gets some mac address from some object outside the code you posted
var MACAddrString = form.mac.value;
// Delete the :'s between MAC address bytes
MACAddrString = MACAddrString.replace(/:/g, '');
// Take the last 3 bytes (6 hex digit symbols)
MACAddrString = MACAddrString.slice(-6);
// Parse the hex string to a number. Second argument indicates base 16.
var MACAddrInt = parseInt(MACAddrString, 16);
// Calculate the pin
var pin = MACAddrInt % 12000;
Wrapping javascript function for access using c# instead of conversion/porting
You could look into using Jurassic for doing that.
Calling a JavaScript function from .NET
$(document).ready(function () { StartCountDown(); }); //start the countdown
function Decrement() {
currentMinutes = Math.floor(secs / 60);
currentSeconds = secs % 60;
if (currentSeconds <= 9) currentSeconds = "0" + currentSeconds;
secs--;
document.getElementById("timerText").innerHTML = "Time Remaining " + currentMinutes + ":" + currentSeconds;
if (secs !== -1) {
setTimeout('Decrement()', 1000);
}
else {
window.location.href = "default.aspx?timeout=1"
}
}
function CheckIfAllQuestionAnswerHasBeenSubmitted() {
var numItems = $('.tblOptions').length;
var flagtocheckcount = 0;
$(".tblOptions").each(function () {
var groupname = $('input[type=radio]:first', this).attr('name');
if (!$("input[name='" + groupname + "']:checked").val()) {
$(this).parents(".tableclass").addClass("border");
var tableid = $(this).closest('table [class^="tableclass"]').attr("id");
}
else {
flagtocheckcount = flagtocheckcount + 1;
}
})
Related
I tried since yesterday to find out the reverse of this formula:
I work with HART (Highway Addressable Remote Transducer) Protocol and the specification said this:
"... for the DEFAULT_VALUE, the constant-expression must resolve to an
unsigned 4-byte or 8-byte integer. example 4-byte TIME_VALUE encoding
for 05:14:26 could be expressed as: DEFAULT_VALUE =
((5*60+14)*60+26)*32000;"
this value is equal with: 603712000 -> to byte array -> 23 FB EA 00
Can anyone please help me to find the reverse formula? for example 444800000 -> to byte array -> 1A 83 1C 00.. this number first is divided with 32000 and it's equal to : 13900, and from here I want to obtain the readable time format: hh:mm:ss (like in the above example).
I made this functions but seems to not work as I expected:
secondsPassedToTime = function (seconds) {
var decimalTime = seconds / 86400;
var hour = decimalTime * 24;
var minutes = (hour % 1) * 60 // --> (hour % 1) -> get fractional part from number: 1.9 = 1 + 0.9
var seconds = (minutes % 1) * 60
hour = (~~hour).toString().length < 2 ? "0" + (~~hour).toString() : (~~hour).toString(); // --> (~~hour) -> get int from float: 1.9 = 1
minutes = (~~minutes).toString().length < 2 ? "0" + (~~minutes).toString() : (~~minutes).toString();
seconds = (~~seconds).toString().length < 2 ? "0" + (~~seconds).toString() : (~~seconds).toString();
var time = hour.toString() + ":" + minutes.toString() + ":" + seconds.toString();
return time;
};
console.log(secondsPassedToTime(13900))
here I get a possible readable format, but when I transform this to byte array is not 1a 83 1c 00 is totally another value.. 1A 82 9F 00. One of these functions doesn't work properly.
timeToHartTimeByteArray = function (time) {
var byteArray = new Array();
var regex = /^[0-9]{2}\:[0-9]{2}\:[0-9]{2}/;
if (time.match(regex)) {
time = time;
}
else {
throw "Invalid format for TIME! Format must be: hh:mm:ss";
}
var time = time.split(":");
var hours = parseFloat(time[0]) * 3600;
var minutes = parseFloat(time[1]) * 60;
var seconds = parseFloat(time[2]);
var finalTime = hours + minutes + seconds;
finalTime = finalTime * 32000;
var hexTime = finalTime.toString(16)
if (hexTime.length != 8) {
var hexTime = "0" + hexTime;
byteArray.push(hexTime.slice(0, 2))
byteArray.push(hexTime.slice(2, 4))
byteArray.push(hexTime.slice(4, 6))
byteArray.push(hexTime.slice(6, 8))
}
else {
byteArray.push(hexTime.slice(0, 2))
byteArray.push(hexTime.slice(2, 4))
byteArray.push(hexTime.slice(4, 6))
byteArray.push(hexTime.slice(6, 8))
}
return byteArray;
};
console.log(timeToHartTimeByteArray("03:51:39"))
I found the problem, it was the first function, the calculation was completely wrong:
secondsPassedToTime = function (seconds) {
var hour = seconds * 0.00027778;
var hh = (~~hour).toString().length < 2 ? "0" + (~~hour).toString() : (~~hour).toString();
var minutes = (hour - hh) * 60.000;
var mm = (~~minutes).toString().length < 2 ? "0" + (~~minutes).toString() : (~~minutes).toString();
var seconds = (minutes - mm) / 0.016667;
var ss = (~~seconds).toString().length < 2 ? "0" + (~~seconds).toString() : (~~seconds).toString();
return (hh + ":" + mm + ":" + ss)
};
console.log(secondsPassedToTime(13900))
And now with this output, the second functions convert to the correct hexadecimal value:
timeToHartTimeByteArray = function (time) {
var byteArray = new Array();
var regex = /^[0-9]{2}\:[0-9]{2}\:[0-9]{2}/;
if (time.match(regex)) {
time = time;
}
else {
throw "Invalid format for TIME! Format must be: hh:mm:ss";
}
var time = time.split(":");
var hours = parseFloat(time[0]) * 3600;
var minutes = parseFloat(time[1]) * 60;
var seconds = parseFloat(time[2]);
var finalTime = hours + minutes + seconds;
finalTime = finalTime * 32000;
var hexTime = finalTime.toString(16)
if (hexTime.length != 8) {
var hexTime = "0" + hexTime;
byteArray.push(hexTime.slice(0, 2))
byteArray.push(hexTime.slice(2, 4))
byteArray.push(hexTime.slice(4, 6))
byteArray.push(hexTime.slice(6, 8))
}
else {
byteArray.push(hexTime.slice(0, 2))
byteArray.push(hexTime.slice(2, 4))
byteArray.push(hexTime.slice(4, 6))
byteArray.push(hexTime.slice(6, 8))
}
return byteArray;
};
console.log(timeToHartTimeByteArray("03:51:40"))
I'd like my countdown timer to show double digits, like "53:00" instead of "53:0". Not sure what's going wrong here? Thank you!
function convertSeconds(s) {
var min = Math.floor(s / 60);
var sec = s % 60;
return nf(min, 2) + ':' + nf(sec, 2);
}
You can use padStart() to make sure a string is a certain length. If it's not it will pad it with whatever you want. In this case 0:
const nf = (n, c) => n.toString().padStart(c, '0');
function convertSeconds(s) {
var min = Math.floor(s / 60);
var sec = (s % 60)
return nf(min, 2) + ':' + nf(sec, 2);
}
console.log(convertSeconds(64))
console.log(convertSeconds(119))
Not sure if you want to pad the minutes of not.
There is also the Intl.NumberFormat() which has an option for minimum digits (though this seems like overkill for this):
console.log(new Intl.NumberFormat('en-US', { minimumIntegerDigits: 2}).format(2));
console.log(new Intl.NumberFormat('en-US', { minimumIntegerDigits: 2}).format(59));
To pad zeroes you can do
function nf(num, places) {
var s = '0' + num;
return s.slice(places * -1);
}
function convertSeconds(s) {
var min = Math.floor(s / 60);
var sec = s % 60;
return nf(min, 2) + ':' + nf(sec, 2);
}
Should get you what you want
If by nf() you mean a function that formats a Number as string of given digits, this can be an implementation of it:
function nf(number, digits) {
var res = number.toString();
while (res.length < digits) {
res = "0" + res;
}
return res;
}
Demo:
function convertSeconds(s) {
var min = Math.floor(s / 60);
var sec = s % 60;
return nf(min, 2) + ':' + nf(sec, 2);
}
function nf(number, digits) {
var res = number.toString();
while (res.length < digits) {
res = "0" + res;
}
return res;
}
console.log(nf(4,2));
The nf() function should be like this:
function nf(num){
if(num < 10){
return "0"+num;
}
return num;
}
console.log(nf(7));
// 07
console.log(nf(11));
// 11
I have a FPS (frames per second) of 30. I have a total FPS so far, lets say 1020. I want to display this as a formatted timecode, as below.
var fps = 30;
var currentFrame = 1020;
var resultString = ; // HH:MM:SS:FF
Are there any Javascript functions built in for formatting like this?
To be clear, I need the string to be formatted as such: HH:MM:SS:FF
Are you looking for a built-in JS function?..
var FF = currentFrame % fps;
var seconds = (currentFrame - FF) / fps;
var SS = seconds % 60;
var minutes = (seconds - SS) / 60;
var MM = minutes % 60;
var HH = (minutes - MM) / 60;
There you go.
It can be done in much simpler way:
function displayTime(currentFrame) {
var fps = 30;
var h = Math.floor(currentFrame/(60*60*fps));
var m = (Math.floor(currentFrame/(60*fps))) % 60;
var s = (Math.floor(currentFrame/fps)) % 60;
var f = currentFrame % fps;
return showTwoDigits(h) + ":" + showTwoDigits(m) + ":" + showTwoDigits(s) + ":" + showTwoDigits(f);
}
function showTwoDigits(number) {
return ("00" + number).slice(-2);
}
console.log("Frame 1020 will be displayed as " + displayTime(1020));
Frame 1020 will be displayed as 00:00:34:00
showTwoDigits
This help function takes a number (example: 6), adds "00" before it, which makes it a string (example: "006"). Then it slices back 2 positions from the end (will give "06").
displayTime
var h
It calculates hours by dividing the frames by 60*60*30 frames per hours. An hour has 60*60*30 frames.
var m
Minutes are calculated in the same way by dividing it by 60*30 frames per minute. But note here that this could result in a number like 80 minutes, because it is the TOTAL amount of minutes. The script has to take in account only the remainder after dividing this amount by 60. Here the modulus comes into play. 80 % 60 will give 20, the number we are looking for.
var s
In a similar way the seconds are calculated by dividing the frames by 30 frames per second and then take it modulus 60 (so that 65 seconds will be represented as 5).
Try this:
var fps = 30;
var currentFrame = 169;
var SS = Math.floor(currentFrame / fps);
var MM = Math.floor(SS / 60);
var HH = Math.floor(MM / 60);
var FF = currentFrame - (SS * fps);
function pad(str, width, what, left) {
str = String(str);
what = String(what);
var w = width - str.length;
if (left) {
return (new Array(w + 1)).join(what) + str;
} else {
return str + (new Array(w + 1)).join(what);
}
}
var i,
timecode = [HH, MM, SS, FF];
for (i = 0; i < timecode.length; i += 1) {
timecode[i] = pad(timecode[i], 2, 0, true);
}
var resultString = timecode.join(':'); // HH:MM:SS:FF
you can also use the date object see here. Just make something like:
var d = new Date( yourframetime + new Date().getTime() );
var str = d.getHours()+':'+ d.getMinutes()+ ':' + d.getSeconds() + .......
than you can use all the string functions of the object, or make your own with it.
Old post, but I was using this recently and a combination of Alexander's and Lucas's code give the correct results. The checked version actually breaks on really large frame counts ( I think due to Math.floor).
Code is:
var fps = 30;
var currentFrame = 169;
var FF = currentFrame % fps;
var seconds = (currentFrame - FF) / fps;
var SS = seconds % 60;
var minutes = (seconds - SS) / 60;
var MM = minutes % 60;
var HH = (minutes - MM) / 60;
function pad(str, width, what, left) {
str = String(str);
what = String(what);
var w = width - str.length;
if (left) {
return (new Array(w + 1)).join(what) + str;
} else {
return str + (new Array(w + 1)).join(what);
}
}
var i,
timecode = [HH, MM, SS, FF];
for (i = 0; i < timecode.length; i += 1) {
timecode[i] = pad(timecode[i], 2, 0, true);
}
var resultString = timecode.join(':'); // HH:MM:SS:FF
For Anyone interested with the swift version of the showTwoDigits function, here is a working code sample:
func showTwoDigits(number:Float) -> (String){
var string = ("00" + String(format:"%.f", number))
var range = Range(start: (advance(string.endIndex, -2)), end: string.endIndex)
var cutStr = string.substringWithRange(range)
return cutStr
}
This function converts to HH:MM:SS:FF correctly :
var convertTime = function (frames, fps) {
fps = (typeof fps !== 'undefined' ? fps : 30 );
var pad = function(input) {return (input < 10) ? "0" + input : input;},
seconds = (typeof frames !== 'undefined' ? frames / fps : 0 );
return [
pad(Math.floor(seconds / 3600)),
pad(Math.floor(seconds % 3600 / 60)),
pad(Math.floor(seconds % 60)),
pad(Math.floor(frames % fps))
].join(':');
}
Demo
var convertTime = function (frames, fps) {
fps = (typeof fps !== 'undefined' ? fps : 30 );
var pad = function(input) {return (input < 10) ? "0" + input : input;},
seconds = (typeof frames !== 'undefined' ? frames / fps : 0 );
return [
pad(Math.floor(seconds / 3600)),
pad(Math.floor(seconds % 3600 / 60)),
pad(Math.floor(seconds % 60)),
pad(Math.floor(frames % fps))
].join(':');
}
document.body.innerHTML = '<pre>' + JSON.stringify({
5 : convertTime(5),
50 : convertTime(50),
126 : convertTime(126),
1156 : convertTime(1156),
9178 : convertTime(9178),
13555 : convertTime(13555)
}, null, '\t') + '</pre>';
See also this Fiddle.
Some time ago, I posted a question how to add times in an emacs-buffer. Now the same thing to be displayed on an ikiwiki page. So the times to add are on the page where the added time should show up. Perhaps the best way would be to have the function in javascript. So my question is, if someone could translate the answer to my elisp question to javascript. The elisp code is:
(defun add-times ()
(interactive)
(let ((minutes 0) (seconds 0))
(save-excursion
(goto-char (point-min))
(while (re-search-forward "\\([0-9]+\\)'\\('\\)?" (point-max) t)
(if (match-string 2)
(setq seconds (+ seconds (string-to-number (match-string 1))))
(setq minutes (+ minutes (string-to-number (match-string 1)))))))
(insert (format "%d'%d''"(+ minutes (/ seconds 60)) (% seconds 60)))))
This?
var seconds = function (str) {
var m = /\d+(?=')/.exec(str);
var s = /\d+(?=")/.exec(str);
return (s ? parseInt(s[0], 10) : 0) +
(m ? parseInt(m[0], 10) * 60 : 0);
}
var totalTime = function (strs) {
var totalSecs = strs.reduce(function (total, str) {
return seconds(str) + total;
}, 0);
var m = Math.floor(totalSecs / 60);
var s = totalSecs - (m * 60);
return (m ? m + "'" : "") +
(s ? s + "\"" : "");
}
totalTime(["5'30\"", "6'15\"", "10'", "1\""]) // 21'46"
I have two values that are used for the amount of time it will take to complete a task. How can I add these values together to come up with a total number of hours and minutes, but still have the value account for 60 minutes equalling one hour?
The two values I'd like to get the sum of and the total value are in HH:MM (00:00) format.
Thanks!
Writing your own time and date functions can get complex. Why re-invent the wheel. Take a look at the excellent http://www.datejs.com/ date library. It handles all date and time related tasks and usage is very simple.
Here's something I had laying around. It allows for an infinite number of arguments, so you could have addTime('01:00') or addTime('01:00', '02:00', '03:00', '04:00'), etc. It's three functions long because it also verifies if the times entered are properly formatted, and if not, then it formats them. (E.g. Ensures that minutes is 2 digits long, and if hours is 1 digit long, then pad it with one zero, etc.)
You can play with it here: http://jsfiddle.net/WyxwU/
It's also here:
var totalTime = addTime('12:34', '56:12', '78:45');
document.write(totalTime);
function addTime()
{
if (arguments.length < 2)
{
if (arguments.length == 1 && isFormattedDate(arguments[0])) return arguments[0];
else return false;
}
var time1Split, time2Split, totalHours, totalMinutes;
if (isFormattedDate(arguments[0])) var totalTime = arguments[0];
else return false;
for (var i = 1; i < arguments.length; i++)
{
// Add them up
time1Split = totalTime.split(':');
time2Split = arguments[i].split(':');
totalHours = parseInt(time1Split[0]) + parseInt(time2Split[0]);
totalMinutes = parseInt(time1Split[1]) + parseInt(time2Split[1]);
// If total minutes is more than 59, then convert to hours and minutes
if (totalMinutes > 59)
{
totalHours += Math.floor(totalMinutes / 60);
totalMinutes = totalMinutes % 60;
}
totalTime = totalHours + ':' + padWithZeros(totalMinutes);
}
return totalTime;
}
function isFormattedDate(date)
{
var splitDate = date.split(':');
if (splitDate.length == 2 && (parseInt(splitDate[0]) + '').length <= 2 && (parseInt(splitDate[1]) + '').length <= 2) return true;
else return false;
}
function padWithZeros(number)
{
var lengthOfNumber = (parseInt(number) + '').length;
if (lengthOfNumber == 2) return number;
else if (lengthOfNumber == 1) return '0' + number;
else if (lengthOfNumber == 0) return '00';
else return false;
}
Here is the simple JS code for this,
var a = "2:50";
var b = "2:15";
var splitTimeStr = function(t){
var t = t.split(":");
t[0] = Number(t[0]);
t[1] = Number(t[1]);
return t;
};
var addTime = function(t1, t2){
var t1Hr = splitTimeStr(t1)[0];
var t1Min = splitTimeStr(t1)[1];
var t2Hr = splitTimeStr(t2)[0];
var t2Min = splitTimeStr(t2)[1];
var rHr = t1Hr + t2Hr;
var rMin = t1Min + t2Min;
if (rMin >= 60)
{
rMin = rMin - 60;
rHr = rHr + 1;
}
if (rMin < 10) rMin = "0" + rMin;
if (rHr < 10) rHr = "0" + rHr;
return "" + rHr + ":" + rMin;
};
document.write(addTime(a, b));
you can validate/play this with code here: http://jsfiddle.net/z24v7/
What you have to do is calculate them to a decimal by that I mean.
Strip out the hour/mins multiple that by 60 + to mins
//strip out the hours
l_hour = Number(l_time$.substr(0, l_pos));
//Strip out the mins
l_min = Number(l_time$.substr(l_pos + 1, l_time$.length));
//add the two values divided by 60 mins
l_time_decimal= Number(Math.abs(l_hour)) + Number(Math.abs(l_min)/60);
Do this for each value then deduct the two figures to give you the difference (i.e time taken). All thats left is convert it back from a decimal to a time
l_difference_in_min = l_difference * 60;
l_time_mins = l_difference_in_min%60;
l_time_hours = (l_difference_in_min - l_mins)/60;
Now just format the two to be HH:MM
I would break the problem into sub-tasks that are reusable. You have to concerns here:
Process a time string in "hh:mm" format: Converting this to minutes makes sense because it seems to be the time granularity at which you're operating.
Format a given number of minutes into a time string in "hh:mm" format.
The fact that you're adding two times together is a diversion from the actual two problems above.
Parse a time string into minutes:
function parseMinutes(s) {
var tokens = s.split(":");
return tokens[0] * 60 + parseInt(tokens[1]);
}
Format minutes into a time string:
function formatMinutes(minutes) {
function pad(n) {
return n > 9
? n
: ("0" + n);
}
var hours = Math.floor(minutes / 60),
mins = minutes % 60;
return pad(hours) + ":" + pad(mins);
}
Then your specific problem can be tackled by:
var sum = formatMinutes(parseMinutes(a) + parseMinutes(b));