Javascript: split time - javascript

I am trying to format a variable value that contains time data and is like the following 00:38:51 or 00:00:59 or 01:25:59
I need to format it like 25m59s or with hour accordingly 1h25m59s 0m59s
I am doing some reading on splits and I have made a start but I am getting confused.
Syntax
Split(expression[,delimiter[,count[,compare]]])
time = "00:38:51"
timeArray = time.split(":",-1)
document.write(timeArray[0]);
Update
I created my own function, I am not sure if this is a good way to do it also;
function formatTime(a) {
var time = a.split(":");
var hours = parseInt(time[0], 10);
var minutes = parseInt(time[1], 10);
var seconds = parseInt(time[2], 10);
var x = document.getElementById("time");
x.innerHTML = hours + "h" + minutes + "m" + seconds + "s"
}
myTime = "00:38:51";
formatTime(myTime);
http://jsfiddle.net/V64dJ/

Try with RegExp
var arr = ["00:38:51","00:00:59","01:25:59"]; // created array due to demonstration
var reg = /(\d+):(\d+):(\d)/, ret = []; // RegExp and result variable declaration
arr.forEach(function(v){
ret = reg.exec(v);
console.log(parseInt(ret[1]) + "h" + parseInt(ret[2]) + "m" + parseInt(ret[3]) + "s"); // 0h38m5s, 0h0m5s, 1h25m5s
});
JSFiddle
NOTE: Using parseInt function during displaying results due to avoid printing 00 instead of 0

This should do it!
function a(time) {
var t = time.split(':'),
s = ['h', 'm', 's'],
i = 0;
for(; i < t.length; i ++) {
t[i] = parseInt(t[i]) == 0 ? '' : parseInt(t[i]) + s[i + s.length - t.length];
}
return t.join('');
}
Fiddle

Related

Generate Reference Number to Google Sheets automatically using Google Apps Script

I am trying to generate a reference number every time a new data in inserted automatically from Google Form.
I would like to generate the format as TMS180001 until the maximum possible reference number which is TMS189999. I could not figure how to format the value/string to 0001 instead of 1 and when I ran below code nothing happened.
function onFormSubmit(e) {
var Time = e.values [0]; //column 1 timestamp
var TMSrefnum = [10]; //column 1 till 9 are other information while
//column 10 is the reference number
if (Time = true); //if timestamp has value then add reference
//number to column 11
var i = 1 ; i < 9999 ; i++;
TMSrefnum = "TMS18" + toString(i);
}
Zero Padding
For zero padding use your own functions e.g.
Number.prototype.pad = function(size) {
var s = String(this);
while (s.length < (size || 2)) {s = "0" + s;}
return s;
}
(9).pad(); //returns "09"
(7).pad(3); //returns "007"
This will allow you to execute the .pad() method on any Number in your script.
Or write a method that looks something like this:
function pad(num, size) {
var s = "000000000" + num;
return s.substr(s.length-size);
}
pad(98); // returns "000000098"
Sources:
https://stackoverflow.com/a/11187738/1139105
https://stackoverflow.com/a/2998822/1139105
See this answer to the question How to output integers with leading zeros in JavaScript.
You'll need to create an extra function outside the onFormSubmit() function (or include the Polyfill).
function pad(num, size) {
var s = num+"";
while (s.length < size) s = "0" + s;
return s;
}
Then you would call
TMSrefnum = "TMS18" + pad(currentEntryNumber, 4);
I managed to produce the reference number from below code.
var sheet1 = ss.getSheets()[0];
function pad(num, size) {
var s = num + "";
while (s.length < size) s = "0" + s;
return s;
}
var valuerange = sheet1.getRange("A1:A").getValues();
var lastrownumber = valuerange.filter(String).length-1;
var TMSNUM = "TMS18" + pad(lastrownumber, 4);

javascript using reduce function

I have the below array
["0,5,p1", "24,29,p2", "78,83,p2", "78,83,p3", "162,167,p2" ]
i want the output as ["5,p1","10,p2","5,p3"] , so p1..3 are video files paying time with start and end time . 0,5 mean p1 profile played for 5 sec and so on.
I want to know what profile take what time in total using ECMA script map,reduce function. Here is what i tried but it doesnt work:
var ca = uniqueArray.reduce(function(pval, elem) {
var spl = elem.split(',');
var difference = Math.round(spl[1] - spl[0]);
return difference;
},elem.split(',')[3]);
I dont think it can be done in one pass, but I could be wrong. I'd go for a 2 step...
Reduce the array to get unique map of pX values
Map the result back to an array in the required format
var input = ["0,5,p1", "24,29,p2", "78,83,p2", "78,83,p3", "162,167,p2" ]
var step1 = input.reduce(function(p,c){
var parts = c.split(",");
if(!p[parts[2]])
p[parts[2]] = 0;
p[parts[2]] += parseInt(parts[1],10) - parseInt(parts[0],10);
return p;
},{});
var result = Object.keys(step1).map(function(e){
return step1[e] + "," + e;
});
console.log(result);
You could use es6 map:
arrayWithNumbers.map(a => {var spl = a.split(','); return (spl[1] - spl[0]) + "," + spl[2]})
For a single loop approach, you could use a hash table for same third parts, like 'p1'. If a hash is given, then update the value with the actual delta.
var array = ["0,5,p1", "24,29,p2", "78,83,p2", "78,83,p3", "162,167,p2"],
hash = Object.create(null),
result = array.reduce(function(r, a) {
var parts = a.split(','),
delta = parts[1] - parts[0],
key = parts[2];
if (!(key in hash)) {
hash[key] = r.push([delta, key].join()) - 1;
return r;
}
r[hash[key]] = [+r[hash[key]].split(',')[0] + delta, key].join();
return r;
}, []);
console.log(result);
I have updated the code. Please check now.
var ca = ["0,5,p1", "24,29,p2", "78,83,p2", "78,83,p3", "162,167,p2" ] .reduce(function(result, elem) {
var spl = elem.split(',');
var difference = Math.round(spl[1] - spl[0]);
var found = false
for (var i = 0 ; i < result.length; i++) {
if (result[i].split(',')[1] == spl[2]) {
result[i] = parseInt(result[i].split(',')[0]) + difference+","+spl[2];
found = true;
}
}
if (!found) result.push(difference+","+spl[2]);
return result;
},[]);
console.log("modified array",ca);

When I use parseInt the result is NaN, why?

I used the link below for convert Jalali to Gregorian:
https://github.com/Mds92/MD.BootstrapPersianDateTimePicker/tree/master/MD.BootstrapPersianDateTimePicker/Scripts
I receive data from user as string.
And this is the code I use:
<script>
var jj = document.getElementById("fromDate1"),
bb = document.getElementById("showMe"),
splitOb, yy, mm, dd;
bb.onclick = function () {
splitOb = jj.value.split("/");
for (var i = 0; i < splitOb.length; i++) {
yy = splitOb[0];
mm = splitOb[1];
dd = splitOb[2];
}
var xx = yy.trim().toString(), nn = mm.trim().toString(), mmm = dd.trim().toString();
var xxx = parseInt(xx, 10);
var nnn = parseInt(nn, 10);
var mjj = parseInt(mmm, 10);
var hello = toGregorian(xxx, nnn, mjj);
alert(hello.gy + "/" + hello.gm + "/" + hello.gd);
/* var gh= "1395";
var ghh = parseInt(gh);
alert(ghh);*/
};
</script>
I used parseInt in my code and unfortunately the result is Nan, I checked my variables, all of them was strings. But when I convert them from string to integer the result is NaN too.
when I set string to my variables manually like this code:
var jjj = "1395";
var yyyt = "05";
var kik = "04";
var xxx = parseInt(jjj, 10);
var nnn = parseInt(yyyt, 10);
var mjj = parseInt(kik, 10);
var hello = toGregorian(xxx, nnn, mjj);
alert(hello.gy + "/" + hello.gm + "/" + hello.gd);
Everything works fine, why?
NaN means Not A Number. Maybe you could eliminate that toString() part.
<script>
var jj = document.getElementById("fromDate1"),
bb = document.getElementById("showMe"),
splitOb, yy, mm, dd;
bb.onclick = function () {
splitOb = jj.value.split("/");
for (var i = 0; i < splitOb.length; i++) {
yy = splitOb[0];
mm = splitOb[1];
dd = splitOb[2];
}
var xxx = parseInt(yy, 10);
var nnn = parseInt(mm, 10);
var mjj = parseInt(dd, 10);
var hello = toGregorian(xxx, nnn, mjj);
alert(hello.gy + "/" + hello.gm + "/" + hello.gd);
/* var gh= "1395";
var ghh = parseInt(gh);
alert(ghh);*/
};
</script>
This could help answer your question. It seems that it's unable to convert the first character or some of the characters to a numerical value. That's what is causing the issue.
I GOT IT !!
The problem was that the string that I get form users was Persian/Arabic. I should change it to English string numbers. I used this code to solve the problem:
function parseArabic(str) {
return Number( str.replace(/[٠١٢٣٤٥٦٧٨٩]/g, function(d) {
return d.charCodeAt(0) - 1632;
}).replace(/[۰۱۲۳۴۵۶۷۸۹]/g, function(d) {
return d.charCodeAt(0) - 1776;
}) );
}
I would be appreciate if you have another customized code to tell me.
Thanks for your consideration.

limit the query exactly with 8 and 7 digits in javascript

i have a little question:
how i can limit or generate the result of a query in 7 or 8 digits
example:
var x = 3143284294
var y = 387520525892
var z = -7632489234892
var w = 34563
result:
var x = 3143284
var y = 3875205
var z = -763248
var w = 3456300 (fill whit "0")
What function or prefix in javascript will use?
tnks(and sorry for my english)
This converts the number to a string and performs string operations on it. Note that repeat is a fairly recent feature of ECMAScript.
function cutNum(n, limit) {
n = n + '';
n = n.substr(0, limit);
if (n.length < limit) {
n = n + '0'.repeat(limit - n.length);
}
return parseInt(n, 10);
}
var x = 3143284294;
cutNum(x, 7); // 3143284
var z = -7632489234892;
cutNum(z, 7); // -763248
var w = 34563;
cutNum(w, 7); // 3456300
Take a look at the slice() method.
var numbers = "01234567890";
var res = numbers.slice(0,6);
alert(res);
Since your sample also includes that are less than 7 digits, you will want to run a logic check first prior to the slice.
var x = "01"
if(x.length < 7)
x = x + "0000000";
x = x.slice(0,6);
alert(x);

Adding a comma at every third number character

In my code I have a variable myCash, which is printed into an h1 element using javaScript's innerHTML. I found a function online that puts a comma after every third character from the end of the number so that the number is easier to read. I've tried for a couple of hours now sending my variable myCash into the function and then print it on the screen. I CANNOT get it to work.
I've tried just alerting the new variable to the screen after page load or by pressing a button, but I get nothing and the alert doesn't even work. Here's the comma insert function:
function commaFormatted(amount) {
var delimiter = ","; // replace comma if desired
amount = new String(amount);
var a = amount.split('.',2)
var d = a[1];
var i = parseInt(a[0]);
if(isNaN(i)) { return ''; }
var minus = '';
if(i < 0) { minus = '-'; }
i = Math.abs(i);
var n = new String(i);
var a = [];
while(n.length > 3)
{
var nn = n.substr(n.length-3);
a.unshift(nn);
n = n.substr(0,n.length-3);
}
if(n.length > 0) { a.unshift(n); }
n = a.join(delimiter);
if(d.length < 1) { amount = n; }
else { amount = n + '.' + d; }
amount = minus + amount;
return amount;
}
now when I want my variable to change I've tried it a few different ways including this:
var newMyCash = commaFormatted(myCash);
alert(newMyCash);
and this:
alert(commaFormatted(myCash);
Where of course myCash equal some large number;
This does absolutely nothing! What am I doing wrong here??
Also,
Try this as a drop in replacement and try alerting the response:
http://phpjs.org/functions/number_format:481
Do you see any errors in the console of your browser (usually f12)?
This is not my function, but I hope it helps you.
function addCommas(nStr)
{
nStr += '';
x = nStr.split('.');
x1 = x[0];
x2 = x.length > 1 ? '.' + x[1] : '';
var rgx = /(\d+)(\d{3})/;
while (rgx.test(x1)) {
x1 = x1.replace(rgx, '$1' + ',' + '$2');
}
return x1 + x2;
}
Usage:
var newMyCash = addCommas( myCash ); alert( newMyCash );
Source: http://www.mredkj.com/javascript/nfbasic.html
You are most likely not passing in a number that contains a decimal, which the function expects.
Working Demo

Categories