Get the difference between two variables - javascript

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.

Related

Change Time format

I have a time string and I want to convert it to have : between the hour and minutes. Any suggestions on how to take the sting and change it. I’m assuming I need to use regular expression but not sure how to format that code. Any suggestions would be great.
var number = '1340';
moment(number).format('hh:mm')
console.log(number)
// The output I want would be 13:40
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.27.0/moment.min.js"></script>
Stick a : before the last 2 digits. This makes the assumption that your minutes are padded with zeroes if not 2 digits long:
console.log('1340'.replace(/\d{2}$/, m => ':' + m));
First off, in the code you show you are outputing the original string not the result from moment.js.
If you want to use moment, you'll need to tell it what format your string is:
var number = '1340';
var time = moment(number, 'hhmm').format('hh:mm')
console.log(time)
var number = '1340';
console.log(number.slice(0, 2)+":"+number.slice(2));
const number = "1340";
const time = `${number.substring(0,2)}:${number.substring(2,4)}`;
console.log(time);
Moment needs a date.
You want something like this
const pad = num => ("00"+num).slice(-2);
const hhmm = str => {
const mm = str.slice(-2)
const hh = str.slice(0,-2)
return `${pad(hh)}:${pad(mm)}`;
};
console.log(hhmm('1340'))
console.log(hhmm('340'))
console.log(hhmm('40'))
console.log(hhmm('0'))
console.log(hhmm(''))
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.27.0/moment.min.js"></script>

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

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

Addition not working in Javascript

I'm really new to Javascript and trying to create a form where I'm running into some trouble...
When I use + it does not add up to the value, instead it just puts it back to back. Ex: 5+10 (510)
Here's my code if you want to take a look at it. I'd appreciate any help since I can't figure this out on my own.
var service = document.getElementById("service");
var serviceprice = service.options[service.selectedIndex].id;
var tech = document.getElementById("tech");
var techprice = tech.options[tech.selectedIndex].id;
var hours = document.getElementById("hours").value;
// The error happens here
var total = techprice * hours + serviceprice;
I also have an html part which the script gets the data from.
That happens whenever you have a string rather than a number. The + operator performs concatenation for strings. Make sure you parse your strings to numbers using parseFloat or parseInt:
var service = document.getElementById("service");
var serviceprice = parseInt(service.options[service.selectedIndex].id, 10);
var tech = document.getElementById("tech");
var techprice = parseInt(tech.options[tech.selectedIndex].id, 10);
var hours = parseInt(document.getElementById("hours").value, 10);
Note that parseInt takes an argument to specify the base. You almost always want base 10.
Try changing this line:
var total = techprice * hours + serviceprice;
to
var total = techprice * hours + parseFloat(serviceprice);
I suspect 'servicePrice' is a string, and it will then try to concatenate the first value (let's say: 100) with the second value (which is, not a number, but a string, let's say 'test'), the result being '100test'.
Try to convert the string to int first with parseInt or to float with parseFloat
This is not especially elegant, but I find it simple, easy, and useful:
var total = -(-techprice * hours - serviceprice);
or even:
var total = techprice * hours -(-serviceprice);
They both eliminate the ambiguous + operator.

Javascript: Mutating "05/01/2013" into "20130501"?

So I have a string that represents a date and I need to change the format of it. This is what I have so far:
function myFunction()
{
var dateto = "05/01/2013";
dateto.replace("/", "");
//now what?
}
It will always originally be in the MM/DD/YYYY format, and I need to change it to a YYYYMMDD format. I'm looking for something on the lines of dateto = dateto[5..8] + dateto[0..1] + dateto[2..3]
. Not sure how to write that in JS though.
You can use some simple string maniuplation
var dateto = "05/01/2013";
var parts = dateto.split('/');
var newDate = parts[2] + parts[0] + parts[1];
Fiddle: http://jsfiddle.net/kvU6H/
This can be done using replace with a regular expression and capture groups:
"05/01/2013".replace(
/(\d{2})\/(\d{2})\/(\d{4})/, // capture data in groups
"$3$1$2") // replace with captured groups
While the above approach works well enough for this specific case, consider a library like moment.js:
moment
.parse("05/01/2013", "MM/DD/YYY") // parse our format
.format("YYYYMMDD") // write target format
You could consider the substring() function where you just provide the beginning and end positions (or indexes) of the desired string in the original string:
function myFunction()
{
var dateto = "05/01/2013";
return dateto.substring(6, 10) + dateto.substring(0, 2) + dateto.substring(3, 5);
}
returns:
20130501
Indexes start from 0 in Javascript (and most programming languages)... so for your string:
string: 0 5 / 0 1 / 2 0 1 3
index: 0 1 2 3 4 5 6 7 8 9

Javascript: Add +1 to number that starts with 0 (like 01, 02, 03) and keep the zero

I like to add (+1) to a number. But problem is my number can sometimes have 0 preceding it. Like 01, 02, 03, 04. So I like result to be:
mockup01 + 1 = mockup02
mockup11 + 1 = mockup12
How can that be achieved? Example of how I would use it would be if I had filename named mockup_01.htm and change it to mockup_02.htm
Thanks!
Maybe this
next = (parseInt(number, 10) + 101).toString().substr(1)
to make a mockup_02.htm out of mockup_01 try this
newName = fileName.replace(/\d+(?=\.)/, function(n) {
return (parseInt(n, 10) + Math.pow(10, n.length) + 1).toString().substr(1)
});
this works with numbers of any length, e.g. mockup_0001, mockup_000001 etc
I'm not a javascript programmer, but it seems like you're mixing up presentation and internal representation. If the "01" is a string, with a corresponding integer variable, you can convert from the string to the integer, add 1, and then make a new string with the desired formatting. This is sometimes referred to as a model-view-controller pattern. The model is the integer variable - it models the internal behavior of numbers. The view is the string - it presents the number in a human readable fashion. The controller handles the numerical operations.
function next_id(input) {
var output = parseInt(input, 10)+1; // parse and increment
output += ""; // convert to string
while (output.length<2) output = "0"+output; // prepend leading zeros
return output;
}
var id = "00";
for (var i=0; i<20; i++) {
console.log(id);
id = next_id(id);
}

Categories

Resources