Change Time format - javascript

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>

Related

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

How to create regex for time with AM/PM in Javascript

How to create a regex for getting only time time in javascript ?
[12/21/2015 1:00:42.016 AM]
I am trying to get
1:00 AM (ie HH:MM AM/PM)
This is what i tried
input.match(/\d+/g) // => [12,21,2015,1,00,42,016]
AM/PM is missing from the result /
It can be done quite simply without the use of a RegExp or library.
var s = '[12/21/2015 1:00:42.016 AM]';
var p = s.split(' ').slice(1);
p[0] = p[0].slice(0, p[0].lastIndexOf(':'));
p = p.join(' ').slice(0, -1);
document.body.textContent = p;
(\d{1,2}:\d{2}):\d{2}\.\d+ ([AP]M)
Now group one will contain the time and group two - AM/PM
See it in action
timeRegex = /(\d{1,2}:\d{2}):\d{2}\.\d+ ([AP]M)/;
found = "[12/21/2015 1:00:42.016 AM]".match(timeRegex);
console.log(found[1]); // => "1:00"
console.log(found[2]); // => "AM"

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 dynamic regex vs hard typed and captures

I've been at this for hours -- I think I need sleep... but no matter how I alter the expression javascript will only capture the 1st and 3rd elements:
var number = 09416;
var mat = "([0-9]+/[0-9]+/[0-9]+\\s+[0-9]+:[0-9]+)\\s+([A-Z]+)\\s+[0-9,]+\\s+(.*?"+number+".+)";
// month / day / year hour : min AMPM byte size filename containing number in middle
var pattern = new RegExp(mat,"gi");
var arr = ['09/07/2010 07:08 PM 1,465,536 BOL09416 BOL31.exe',
'09/06/2010 12:13 PM 110,225 BOL09416_BOL030.exe',
'09/08/2010 04:46 AM 60,564 BOL09416_BOL32.exe',
'09/08/2010 01:08 PM 63,004 bol09416_bol33.exe']
for (var i=0;i<arr.length;i++){
var match = pattern.exec(arr[i]);
alert(match);
}
It is all spaces (no tabs), I've rewriten the regex to be as explainatory as possible... It correctly matches on arr[0] and arr[2], but nulls on the other two.
Tried looking for possible typo's, trying different .+,.*,.+? etc. All online matchers show that it should be working: Example
Anybody have any ideas as to what I'm missing?
====================
Update:
Going through all the awesome suggestions I am stumped even further:
var match = arr[i].match(/([0-9]+\/[0-9]+\/[0-9]+\s+[0-9]+:[0-9]+)\s+([A-Z]+)\s+[0-9,]+\s+(.*?09416.+)/g);
gives match[0] = full string match[1] = undefined. Basically no captures.
where as:
var match = /([0-9]+\/[0-9]+\/[0-9]+\s+[0-9]+:[0-9]+)\s+([A-Z]+)\s+[0-9,]+\s+(.*?09416.+)/g.exec(arr[i]);
DOES return match[0] = full string, match[1] = date, and so on.
So I guess my real question is how to include dynamically made RegExpressions, and have multiple captures? As the only difference between:
var number = "09416";
var mat = "([0-9]+/[0-9]+/[0-9]+\\s+[0-9]+:[0-9]+)\\s+([A-Z]+)\\s+[0-9,]+\\s+(.*?09416.+)";
var pattern = new RegExp(mat,'g');
and
/([0-9]+\/[0-9]+\/[0-9]+\s+[0-9]+:[0-9]+)\s+([A-Z]+)\s+[0-9,]+\s+(.*?09416.+)/g.exec(arr[i]);
is that I hard-typed the number.
var number = 09416;
// month / day / year hour : min AMPM byte size filename containing number in middle
var mat = '^(\d{2}\/\d{2}\/\d{4})\s+(\d{2}:\d{2}\s*[AP]M)\s+((\d+[\d,]?))\s+(.' + number + '.*)$';
var pattern = new RegExp(mat);
var arr = ['09/07/2010 07:08 PM 1,465,536 BOL09416 BOL31.exe',
'09/06/2010 12:13 PM 110,225 BOL09416_BOL030.exe',
'09/08/2010 04:46 AM 60,564 BOL09416_BOL32.exe',
'09/08/2010 01:08 PM 63,004 bol09416_bol33.exe']
for (var i=0;i<arr.length;i++){
var match = arr[i].match(pattern);
console.log(match);
}
Use string.match instead of regex.exec.
Edited
I've removed the global and it worked like it should be. I've also rewritten the regex but it's quite close to yours (not a big deal).
Look at the output by firebug below:
["09/08/2010 04:46 AM ...,564 BOL09416_BOL32.exe", "09/08/2010", "04:46 AM", "60,564", "564", "BOL09416_BOL32.exe"]
0 "09/08/2010 04:46 AM ...,564 BOL09416_BOL32.exe" //whole match
1 "09/08/2010" //date
2 "04:46 AM" //time
3 "60,564" //bytes
4 "564" // last digit of bytes (i can't take this off. but it's harmless)
5 "BOL09416_BOL32.exe" //name of file
I would suggest you try Regexr to build the expression.
try this
([0-9]+/[0-9]+/[0-9]+ +?[0-9]+:[0-9]+) +?([A-Z]+) +?[0-9,]+ +?(.*?09416.*)
Try this regex:
new RegExp('([0-9]+/[0-9]+/[0-9]+\\s+[0-9]+:[0-9]+)\\s+(AM|PM)\\s+([0-9,]+)\\s+([^0-9]*'+number+'.+)','gi')
Time
AM/PM
File size
File name

Categories

Resources