Best way to normalize time in JS - javascript

I have some data that's inconsistent. It's all time related but I have some records that shows 3pm others 14:00.
Is there an easy way to normalize that in JS?
Thanks

This function will return you a 24-hour-formatted time
function normaliseTime(time) {
// If there is AM/PM in the string, do conversion
if (time.toUpperCase().indexOf('M') >= 0) {
// Remove the AM/PM text and split the hour and minute
var tmArray = time.replace(/\D/g, '').split(':');
// If PM, add 12 to the hour
if (time.toUpperCase().indexOf('PM') >= 0) {
tmArray[0] = parseInt(tmArray[0]) + 12;
}
// If minutes were not provided (i.e., 3PM), add 00 as minutes
if (tmArray.length < 2) {
tmArray[1] = '00';
}
return tmArray.join(':');
}
// If there was no AM/PM in the input, return it as is
return time;
}

Related

How to compare two times in javascript

I'm struggling to compare two times.
I need to print Current class going based on the current time.
Example: current time based class going on the college/school
var now = new Date();
var TwentyFourHour = now.getHours();
var hour = now.getHours();
var min = now.getMinutes();
var mid = 'PM';
if (min < 10) {
min = "0" + min;
}
if (hour > 12) {
hour = hour - 12;
}
if (hour == 0) {
hour = 12;
}
if (TwentyFourHour < 12) {
mid = 'AM';
}
Current_time = hour + ':' + min + ':' + mid;
start_time = "09:00:PM";
end_time = "10:00:PM";
if (parseInt(start_time) <= parseInt(Current_time) || parseInt(end_time) >= parseInt(Current_time)) {
console.log("C programming class is going");
} else {
console.log("No class are avalible");
}
OUTPUT:
C programming class is going....
It seems you are looking for the shortest path to have your homework done.
Please check the references for Date function:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/Date
Some tips:
Make sure you understand how the Date object is created. You can use strings!
If you want to define date manually using each day, month , value, you can!
Check your strings.. are you sure "09:00:PM" is a valid string for date?
Are you sure you can use parseInt for parsing dates?
Anyway, you need to do more research.
The easiest way to check if a time is between a start and an end time is to store the time using unix time(https://en.wikipedia.org/wiki/Unix_time). It represents the time in seconds after 00:00:00 UTC on 1 January 1970. so you can do the following:
const startTime = 1624802400 // 27.6.21 16:00
const endTime = 1624809600 //27.6.21 18:00
const currentTime = Date.now()/1000
if(currentTime < endTime && currentTime > startTime){
console.log('Class is going')
}
if(currentTime > endTime){
console.log('Class ended')
}
if(currentTime < startTime){
console.log('Class has not started')
}
Date.now() returns the current time in milliseconds so you need to divide it by 1000

Check if time is falling under specific timeframe

I have a variable that stores a time value.
var cabtime = ["09:30:00"];
Variable time value is in 24-hour clock. That means 02:30:0PM will come as 14:30:00.
I want to check if the variable time falls under 08:00AM to 10:00AM window. If yes then I'll do an action.
Any pointers in this regard?
You could parse the time into seconds since midnight using:
var cabtime = ["HH:MM:SS"] // in 24hr time
function parseTime (string) {
parts = string.split(':').map(x => parseInt(x))
seconds = parts[0] * 3600 + parts[1] * 60 + parts[0]
return seconds
}
Then you can parse the time and the upper/lower bounds, and test using:
time = parseTime(cabtime[0])
lower = parseTime('08:00:00')
upper = parseTime('10:00:00')
if (time >= lower && time <= upper) {
print('Inside the range')
}
You can solve it easily by converting your strings to Date objects and compare them than.
var cabtime = ["09:30"];
function checkTimeRange(time, from, to, reldate) {
if (undefined === reldate) {
reldate = '0000T'; // the date the time strings are related to
}
let dtime = new Date(reldate + time);
let dfrom = new Date(reldate + from);
let dto = new Date(reldate + to);
return dfrom <= dtime && dtime <= dto;
}
checkTimeRange(cabtime[0], '08:00', '10:00'); // returns true
If you have full dates (e.g. '2019-07-25T09:30:00') instead of just the clock time you should provide for the parameter `reldate' an empty string.
* update: changed the wrong date format to standard format
* update: changed the date format again to be more fancy

How to humanize duration in angularjs?

I am using momentjs and moment-duration-format to show duration in Y M D HH:mm:ss format depending on duration if it includes year, month, day, hour, minutes & seconds, with ngTable sorting and filter on this field.
Code
$scope.getTableDataDuration = function(item) {
if (angular.isDefined(item) && item != null) {
var tmp = "";
if (item > 31536000) { //year
tmp = moment.duration(item, "year").format("Y M D h:mm:s");
return tmp;
} else if (item > 2628000) { //month
tmp = moment.duration(item, "month").format("M D h:mm:s");
return tmp;
} else if (item >= 86400) { //day
tmp = moment.duration(item, "days").format("D h:mm:s");
return tmp;
} else if (item < 60) {
return item;
} else if (item < 3600) { //minute
tmp = moment.duration(item, "minutes").format("h:mm:s");
return tmp;
}
}
return;
}
Plunker link
Update
So for example:
duration in seconds 331 should show 05:51
duration in seconds 7245 should show 02:01:25
similarly till years
Given a duration, I need to humanize it similar to above example
I believe that you misunderstood the documentation. I did not use moment-duration personally, but from the documentation on GitHub it seems that what you want to use is this
moment.duration(99544, "seconds").format("D h:mm:s");
It informs the Duration plugin, that the input number is in seconds, which it is. And then you format it via the provided format string.
See this example https://github.com/jsmreese/moment-duration-format#weeks
Here he uses moment.duration(123, "days").format("w W", 2); which basically says "I have 123 days and I want to convert it to number of weeks"

change time string of HH:mm am/pm to 24 hour time

I get a variable string like so:
8:45 am
And want, if it is pm, to convert it to 24 hour time. So that I can then drop the am/pm and use it with something else.
I can drop the am/pm quite easily like this:
function replaceEnds(string) {
string = string.replace("am", "");
string = string.replace("pm", "");
return string;
}
But of course if I do that, I don't know if the string is am or pm, so I don't know to add 12 hours on to the string to make it 24 hour.
Anyone know how I could resolve this? I absolutely cannot change the input that I get of the variable, it'll always be the hour (in 12 hour time), minutes, and am or pm.
Using moment.js:
moment(string, 'h:mm a').format('H:mm');
If you want to do it manually, this would be my solution:
function to24Hour(str) {
var tokens = /([10]?\d):([0-5]\d) ([ap]m)/i.exec(str);
if (tokens == null) { return null; }
if (tokens[3].toLowerCase() === 'pm' && tokens[1] !== '12') {
tokens[1] = '' + (12 + (+tokens[1]));
} else if (tokens[3].toLowerCase() === 'am' && tokens[1] === '12') {
tokens[1] = '00';
}
return tokens[1] + ':' + tokens[2];
}
The manual solution is harder to understand, is less flexible, is missing some error checking and needs unit tests. In general, you should usually prefer a well-tested popular library's solution, rather than your own (if a well-tested library is available).
Without using any additional JavaScript libraries:
/**
* #var amPmString - Time component (e.g. "8:45 PM")
* #returns - 24 hour time string
*/
function getTwentyFourHourTime(amPmString) {
var d = new Date("1/1/2013 " + amPmString);
return d.getHours() + ':' + d.getMinutes();
}
So for example:
getTwentyFourHourTime("8:45 PM"); // "20:45"
getTwentyFourHourTime("8:45 AM"); // "8:45"
In case you're looking for a solution that converts ANY FORMAT to 24 hours HH:MM correctly.
function get24hTime(str){
str = String(str).toLowerCase().replace(/\s/g, '');
var has_am = str.indexOf('am') >= 0;
var has_pm = str.indexOf('pm') >= 0;
// first strip off the am/pm, leave it either hour or hour:minute
str = str.replace('am', '').replace('pm', '');
// if hour, convert to hour:00
if (str.indexOf(':') < 0) str = str + ':00';
// now it's hour:minute
// we add am/pm back if striped out before
if (has_am) str += ' am';
if (has_pm) str += ' pm';
// now its either hour:minute, or hour:minute am/pm
// put it in a date object, it will convert to 24 hours format for us
var d = new Date("1/1/2011 " + str);
// make hours and minutes double digits
var doubleDigits = function(n){
return (parseInt(n) < 10) ? "0" + n : String(n);
};
return doubleDigits(d.getHours()) + ':' + doubleDigits(d.getMinutes());
}
console.log(get24hTime('6')); // 06:00
console.log(get24hTime('6am')); // 06:00
console.log(get24hTime('6pm')); // 18:00
console.log(get24hTime('6:11pm')); // 18:11
console.log(get24hTime('6:11')); // 06:11
console.log(get24hTime('18')); // 18:00
console.log(get24hTime('18:11')); // 18:11
I've use something similar to this
//time is an array of [hh] & [mm am/pm] (you can get this by time = time.split(":");
function MilitaryTime(time){
if(time[1].indexOf("AM")!=-1){
//its in the morning, so leave as is
return time;
}else if(time[0]!="12"){
//If it is beyond 12 o clock in the after noon, add twelve for military time.
time[0]=String(parseInt(time[0])+12);
return time;
}
else{
return time;
}
}
Once you get your time returned, you can alter the text in any way you want.

Adding setUTCDate() to replace "computers" time

I followed this tutorial, but I wanted to just be able to set a date and have it countdown to that date.
Even so, it would just base it off my computer's time; how can I make it so it's standard for everyone?
He mentioned setUTCDate() but I have no idea how to implement it?
Here's some code to get you started. It gets the UTC time and alert's it, formatted:
// By default, JS does not pad times with zeros
function checkTime(i) {
if(i<10) i='0'+i;
return i;
}
// Set current UTC time
var d = new Date();
var now = checkTime(d.getUTCHours()) + ':' +
checkTime(d.getUTCMinutes()) + ':' +
checkTime(d.getUTCSeconds());
// Output
alert(now);
Here's a JSFiddle.
Remember: UTC != GMT (read on if you want this to always match the UK time).
BST (when the clocks go forward) will need to be factored in for anyone in the UK wanting to use this solution.
Here's a function I wrote earlier:
// Function returning 0 or 1 depending on whether BST is in effect
function isBSTinEffect()
{
var d = new Date();
// Loop over the 31 days of March for the current year
for(var i=31; i>0; i--)
{
var tmp = new Date(d.getFullYear(), 2, i);
if(tmp.getDay() == 0) { lSoM = tmp; break; }
}
// Loop over the 31 days of October for the current year
for(var i=31; i>0; i--)
{
var tmp = new Date(d.getFullYear(), 9, i);
if(tmp.getDay() == 0) { lSoO = tmp; break; }
}
if(d < lSoM || d > lSoO) return 0;
else return 1;
}
To factor in BST, put that function before // Set current UTC time and change checkTime(d.getUTCHours()) to checkTime(d.getUTCHours()+isBSTinEffect())

Categories

Resources