Add 0 before single digit number of time format [duplicate] - javascript

This question already has answers here:
Adding "0" if clock have one digit
(9 answers)
Closed 3 years ago.
How can we add 0 before single digit number of time format.
Like if I have a time "0:3:25" (hh:mm:ss) format to convert into "00:03:25"

You shouldn't overcomplicate this:
const time = "0:3:25";
const paddedTime = time.split(':').map(e => `0${e}`.slice(-2)).join(':')
console.log(paddedTime)
split the string by semicolons (:), that yields an array (hours, minutes, seconds). map this array with a function that adds a 0 before every item in the array, and slice the last two digits (you get an array again). Then join the resulting array by semicolons (and you get a string).
Or you could use a regex instead of the split:
const time = "0:3:25";
const paddedTime = time.match(/\d+/g).map(e => `0${e}`.slice(-2)).join(':')
console.log(paddedTime)
The last part is the same with regex (map, slice, join).
And you also could use the padStart() (JavaScript built-in function):
const time = "0:3:25";
const paddedTime = time.split(':').map(e => e.padStart(2, 0)).join(':')
console.log(paddedTime)
padStart() on MDN: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/padStart

You can do something like below (Explanations included):
const time = '0:3:25';
const correctedTime = parseTime(time);
console.log(correctedTime);
function parseTime(time){
return time
.split(':') // Split them into array as chunk of [hour, minute, second]
.map(pad) // Map them with `pad` function below
.join(':'); // Join them back into 'hh:mm:ss'
}
function pad(n){
return parseInt(n) < 10 // If number less than 10
? '0' + n // Add '0' in front
: n; // Else, return the original string.
}

you can add split the existing time string on the ":", then for each portion, add the "0" then take the last two characters. Then simply join the portions back into a striung.
let time = "0:3:25";
function updateTime(){
let newTimePortions = [];
let timePortions = time.split(":");
timePortions.forEach(function(portion,index) {
newTimePortions[index] = ("0" + portion).slice(-2)
})
return newTimePortions.join(':')
}
console.log(updateTime()); // gives 00:03:25

Please try below code
var dateinfo="0:3:25";
var newdate=dateinfo.split(":");
var hdate=newdate[0];
var mdate=newdate[1];
var sdate=newdate[2];
if(hdate.length == 1 ){
hdate="0"+hdate;
}
if(mdate.length == 1 ){
mdate="0"+mdate;
}
if(sdate.length == 1 ){
sdate="0"+sdate;
}
dateinfo=hdate+":"+mdate+":"+sdate;
This is work for me

Related

This filter is not returning expected result

function get20(arr){
let result = arr.filter((theArtist) => {
let birth = Number(theArtist.years.splice(0,3))
let death = Number(theArtist.years.splice(7,10))
return birth >= 1900 && death <= 2000;
})
return result;
}
This keeps giving me the error "theArtist.years.splice is not a function" I do not understand why it isn't taking the first four and last four letters of the "years" string and turning them into numbers. the years string looks like "1971 - 1984"
You should use substring on strings (splice is a similar function for arrays). Also note your indexes were off by 1 !
var years = "1971 - 1984";
let birth = Number(years.substring(0,4))
let death = Number(years.substring(7,11))
console.log(birth,death)
Splice is a method for arrays, not strings. Try this:
years = theArtist.years.split('')
let birth = Number(years.splice(0,4))
let death = Number(years.splice(7,4))
Alternatively, use substring.
let birth = Number(theArtist.years.substring(0,4))
let death = Number(theArtist.years.substring(7,11))
Use slice instead splice:
'1971 - 1984'.slice(0,4) // '1971'
'1971 - 1984'.slice(7,11) // '1984'

Format Whole Numbers JavaScript with Commas [duplicate]

This question already has answers here:
How to format a number with commas as thousands separators?
(50 answers)
Closed 2 years ago.
I want to format a number (225121894) so its formatted as 225,121,894 I pull all the numbers from a JSON and sort and process.
Here is my code
function getTestStats(jsonData)
{
let totalTest = 0
let totalCases = 0
jsonData.map(covid =>
{
if(covid.tested !== "NA") totalTest += Number(covid.tested)
})
document.getElementById('covidTestStatPG').innerHTML += `${totalTest}`
}
Try using Number.toLocaleString(). Not only does this handle the problem of comma-separation, but it handles any type of locale-standard display settings. Below, I use en-US, but not every country/region formats commas the same, so this allows you to change as needed (i.e., to en-IN for Indian-English, etc.) without coding it up yourself everytime...
var number = 123456789;
console.log(number.toLocaleString('en-US'));
/*
CODE FOR NUMBER FORMAT
*/
function numFormat(x) {
return x.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
}
console.log( numFormat(224405) );
/*
YOUR CODE
*/
var jsonData = [{tested:"225121894"}]; // Dummay JSON Data
function getTestStats(jsonData)
{
let totalTest = 0
let totalCases = 0
jsonData.map(covid =>
{
if(covid.tested !== "NA") totalTest += Number(covid.tested)
})
document.getElementById('covidTestStatPG').innerHTML += `${numFormat(totalTest)}`
}
getTestStats(jsonData)
<div id="covidTestStatPG">🎁</div>
You may want to check out Intl.NumberFormat.
I've used it before as follows (this is typescript but you get the idea):
const locale = "en-US";
static formatNumber(rawNumber?: number) {
return rawNumber ? Intl.NumberFormat(locale).format(rawNumber) : "-";
}

Get the difference between two variables

I have an object and Hours is saved as a string . I need to convert the string to hours and then get the difference between the 2 variables.
const groupSchedule=[
{"days":"sat","Hourfrom":"15:00","Hourto":"19:00"},
{"days":"sun","Hourfrom":"15:00","Hourto":"19:00"},
{"days":"mon","Hourfrom":"15:00","Hourto":"19:00"},
]
function numberOfHoursInWeek(groupSchedule) {
let hours = 0;
for (const gSchedule of groupSchedule) {
let hour = gSchedule.Hourto.to - gSchedule.Hourfrom;
console.log(hour);
hours += hour;
}
return hours;
}
Problem in converting string to hour (NAN)
I tried to write in a very verbose way. You could do something like this:
const hoursTo = "19:33";
const hoursFrom = "14:55";
const hoursToArray = hoursTo.split(":");
const hoursFromArray = hoursFrom.split(":");
const hoursToDate = new Date(0, 0, 0, hoursToArray[0], hoursToArray[1], 0, 0);
const hoursFromDate = new Date(0, 0, 0, hoursFromArray[0], hoursFromArray[1], 0, 0);
const difference = Math.abs(hoursToDate - hoursFromDate) / 36e5;
console.log(hours) //4.633333333333334;
The basic issue is that you are taking gSchedule.hourTo and gSchedule.hourFrom and trying to perform arithmetic with them when they are string values. You need to split the string and extract a numeric type to perform this type of mathematical calculation.
In this case the relevant numeric portion is the hours portion of the HH:MMstring, so using the split function with : as a delimiter will return a list of two string, one string of hours and one of minutes. We can then parse the hours string to get an int, float, or other numeric type.
//split time strings on the ':'
let hrToSplit = gSchedule.hourTo.split(':')
let hrFromSplit = gSchedule.hourFrom.split(':')
//parse time strings to extract hour as int
let hrToNum = parseInt(hrToSplit[0], 10)
let hrFromNum = parseInt(hrFromSplit[0], 10)
//perform whatever math is needing using the numbers themselves, not the strings
console.log(hrToNum + hrFromNum)
If you want to do some further reading on different approaches beyond the answers you got here, this is a similar question that may be useful to reference.

How can I convert a time into the correct format? [duplicate]

I am receiving a string in this format 'HH:mm:ss'. I would like to remove the leading zeros but always keeping the the last four character eg m:ss even if m would be a zero. I am formatting audio duration.
Examples:
00:03:15 => 3:15
10:10:10 => 10:10:10
00:00:00 => 0:00
04:00:00 => 4:00:00
00:42:32 => 42:32
00:00:18 => 0:18
00:00:08 => 0:08
You can use this replacement:
var result = yourstr.replace(/^(?:00:)?0?/, '');
demo
or better:
var result = yourstr.replace(/^0(?:0:0?)?/, '');
demo
To deal with Matt example (see comments), you can change the pattern to:
^[0:]+(?=\d[\d:]{3})
If you use 1 h instead of two you will not get the leading 0.
h:mm:ss
Another option is to use moment.js libary.
This supports formats such as
var now = moment('1-1-1981 2:44:22').format('h:mm:ss');
alert(now);
http://jsfiddle.net/8yqxh5mo/
You could do something like this:
var tc =['00:03:15', '10:10:10','00:00:00','04:00:00','00:42:32','00:00:18','00:00:08'];
tc.forEach(function(t) {
var y = t.split(":");
y[0] = y[0].replace(/^[0]+/g, '');
if(y[0] === '') {
y[1] = y[1].replace(/^0/g, '');
}
var r = y.filter(function(p) {return p!=='';}).join(':');
console.log(r);
});
Divide the time in 3 parts. Remove the leading zeroes from first part, if the the first part is empty remove the leading zeroes from the second part otherwise keep it. Then join all of them discarding the empty strings.
I had a problem with ZUL time when simply format with one small 'h' moment(date).format('h:mm A') cuts first digit from time:
and my const arrivalTime = "2022-07-21T12:10:51Z"
const result = moment(arrivalTime).format(('h:mm A')) // 2:10 PM
Solution for that was converting that to ISO format and then format:
const arrivalTimeIsoFormat = arrivalTime.toISOString()
const result = moment(arrivalTimeIsoFormat, "YYYY-MM-DDTHH:mm:ss.SSS").format(('h:mm A')) // 12:10 PM

Check array elements has value

For example I have code like this:
var myArr="14:44:45".split(":");
But sometimes time value doesn't have "seconds" information.
var myArr="14:44".split(":");
Basicly sometimes the string has value of "seconds" and sometimes has not.So how can I check if the myArr[2] has value.What is the best practice for that?
if(myArr.length === 3)
Is it okay?
Edit: or
if(myArr[2])
Your approach is correct
A better approach is destructuring the array and checking for the variable seconds
let [h, m, s] = "14:44:45".split(":");
if (s) console.log('Has seconds');
let [hh, mm, ss] = "14:44".split(":");
if (!ss) console.log("Doesn't have seconds");
Resource
Destructuring assignment
As others have said, your approach is almost fine. You might want to check that the length is greater than 2 rather than equal to 3, but that might never be an issue.
But I have an alternate suggestion:
const timeParts = time => {
const [hours, minutes = 0, seconds = 0] = time.split(':').map(Number)
return {hours, minutes, seconds}
}
console.log(timeParts('14:44:45')) //=> {hours: 14, minutes: 44, seconds: 45}
console.log(timeParts('14:45')) //=> {hours: 14, minutes: 45, seconds: 0}
Rather than doing an explicit check this simply gives default values for the minutes and seconds. If you don't want the numeric conversion replace the first line of the function with
const [hours, minutes = '00', seconds = '00'] = time.split(':')
Example 1 uses split() and .length` and a ternary operator to compare length of array. If you only have one or two timestamps this is sufficient.
Example 2 uses .map() to iterate through an array of timestamps. Each timestamp is compared by the same function from the the previous example. If you have more than one timestamp to check try this example.
Example 3 is like the previous example and it will append :00 to any timestamp that needs it. If you have more than one timestamp and actually want to fix them as well try this example.
Demo
//~~~~~~~~~~~~If you have one or two timestamps~~~~~~~~~~~~~Example 1
function sec(stamp) {
return stamp.split(':').length < 3 ? 'No Seconds':'Has Seconds';
}
let r0 = sec("14:44:45");
let r1 = sec("14:44");
console.log(r0);
console.log(r1);
//~~~~~~~~~~~~If you have more than one timestamp~~~~~~~~~~~~Example 2
const times = ["14:44:45", "14:44", "20:59:10", "7:23:32", "3:04", "15:46", "8:18"];
const secChk = times.map(function(time) {
return time.split(':').length < 3 ? 'No Seconds':'Has Seconds';
});
console.log(secChk);
//~~~~~If you have more than one timestamp you want to fix~~~~Example 3
const secFix = times.map(function(time, index) {
return time.split(':').length < 3 ? '['+index+']: '+time+':00 - Fixed':'['+index+']: '+time;
});
console.log(secFix);

Categories

Resources