1

I need a function to convert time in text from a format with day-part letters to digits. E.g. 4:15PM -> 16:15, 4:15AM -> 4:15AM. Currently I have the following solution

function formatTime(text){
	var find = '([0-9]|0[0-9]|1[0-9]|2[0-3]):[0-5][0-9] (AM|PM)';
	
	var reg = new RegExp(find, 'g');
	
	pos = 0;

	var result;
	var formatedText = "";
	while((result = reg.exec(text)) !== null) {
		if(result[2] == "PM"){
			var hours= parseInt(result[0], 10);
			hours = hours + 12;
			var hoursStr = hours.toString();
			var newTime = hoursStr + result[0].substring(result[1].length,result[0].length - 3);
			
			formatedText += newTime;
			pos = reg.lastIndex;
		} else {
			formatedText += text.replace("AM","").substring(pos, reg.lastIndex);
			pos = reg.lastIndex;
		}
	}
	
	if(pos < text.length){
		formatedText += text.substring(pos, text.length);
	}
	
	return formatedText;
}

console.log(formatTime("Some Text (11:00AM - 1:00PM)"));

I makes nicely cases like console.log(formatTime("Some Text (11:00AM - 1:00PM)"));

But I strugle to make it process console.log(formatTime("Some Text (11:00 AM - 1:00 PM)"));

4
  • stackoverflow.com/questions/14415618/… Commented Dec 21, 2016 at 10:20
  • E.g. 4:15PM -> 16:15, 4:15AM -> 4:15AM So if it's it PM you want to convert the hour, but if it's AM you want to leave the "AM"" in the result? Commented Dec 21, 2016 at 10:31
  • yes, I need it to be formatted like this. Commented Dec 21, 2016 at 11:08
  • How come you didn't try to use a library such as moment.js? Why reinvent the wheel and waste your valuable time? Libraries exist for a reason, don't hesitate to use them. Arguments such as "it's too big for my needs" or "mine works faster" aren't real arguments. People create free software, we should use it - especially if it saves us our time and lets us focus on our work. Commented Dec 21, 2016 at 11:37

2 Answers 2

1

This works for your examples. I've added \\s? to the regex and made a minor change in the logic of cutting time (-2 instead of -3). Also I've moved variables definition to the beginning of the function to reflect hoisting in JavaScript.

function formatTime(text){
    var find = '([0-9]|0[0-9]|1[0-9]|2[0-3]):[0-5][0-9]\\s?(AM|PM)';            
    var reg = new RegExp(find, 'g');            
    var pos = 0;
    var formatedText = "";
    var result, hours, hoursStr, newTime;           

    while ((result = reg.exec(text)) !== null) {
        if (result[2] === "PM") {
            hours= parseInt(result[0], 10);
            hours = hours + 12;
            hoursStr = hours.toString();
            newTime = hoursStr + result[0].substring(result[1].length, result[0].length - 2);

            formatedText += newTime;                    
        } else {
            formatedText += text.replace("AM","").substring(pos, reg.lastIndex);

        }

        pos = reg.lastIndex;
    }

    if (pos < text.length) {
        formatedText += text.substring(pos, text.length);
    }

    return formatedText;
}
Sign up to request clarification or add additional context in comments.

1 Comment

Works why, because you did what? Why did you not clean up his regexp for him, or fix it to use a regexp literal as he should? What is the purpose of the g flag, and why is there a loop around reg.exec?
0

Here's an easier way to do this: Just use two functions. One to convert the hours, and another to match against PM times along with the replace() function.

Easy does it...

function convertTime12to24(time12h) {
  const [time, modifier] = time12h.split(' ');

  let [hours, minutes] = time.split(':');

  if (hours === '12') {
    hours = '00';
  }

  if (modifier === 'PM') {
    hours = parseInt(hours, 10) + 12;
  }

  return hours + ':' + minutes;
}


function formatTime(i_string) {
  console.log(i_string.replace(/([0-9]|0[0-9]|1[0-9]|2[0-3]):([0-5][0-9])(PM)/gi, function newDate(x) {

    return convertTime12to24(x.replace("PM", " PM"))
  }));
}
formatTime("The time is now 4:15PM");
formatTime("The time is now 12:15PM");
formatTime("The time is now 4:00AM");
formatTime("The time is now 12:00AM");
formatTime("The time is now 11:00PM");

5 Comments

But according to OP, he wants to retain the "AM". Also, your code seems to be removing the space following the dash.
I simply wanted to point in the right direction - this site really isn't for creating production quality answers for people -- its for helping solve their programming issues -- since I dont know/care how their algorithm works or how it manages to derive the output, I simply noted the typo and then made a correction where it appeared there was a hard coded value which depended on the typo. I would probably do it a different way using the : as a separator then just adding 12 if its PM to the hour part but whatever
@torazaburo also it does not say that they want to retain the AM/PM in the OP -- it says 4:15PM -> 16:15
The original post clearly says 4:15AM -> 4:15AM, preserving the "AM", and the OP confirmed that in a comment.
im re-writing the code to make it way easier -- this is a terrible answer anywas

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.