0

I've written this function to get the current time, like a custom time stamp, and I'm getting an unexpected result. When the current minute is anywhere from "00" to "09", the Javascript method getMinutes() returns from "0" to "9" respectively. I'm using a switch to get this cases and add another "0" in front, but it's not working as expected.

This is my full code:

	function horaActual() {
	  var d = new Date();
	  var dia = '';
	  var hora = '';
	  var minutos = '';

	  switch (d.getDay()) {
	    case 0:
	      dia = 'Dom';
	      break;
	    case 1:
	      dia = 'Lun';
	      break;
	    case 2:
	      dia = 'Mar';
	      break;
	    case 3:
	      dia = 'Mie';
	      break;
	    case 4:
	      dia = 'Jue';
	      break;
	    case 5:
	      dia = 'Vie';
	      break;
	    case 6:
	      dia = 'Sáb';
	      break;
	  };

	  switch (d.getHours()) {
	    case 0, 1, 2, 3, 4, 5, 6, 7, 8, 9:
	      hora = '0' + String(d.getHours());
	      break;
	    default:
	      hora = String(d.getHours());
	      break;
	  };

	  switch (d.getMinutes()) {
	    case 0, 1, 2, 3, 4, 5, 6, 7, 8, 9:
	      minutos = '0' + String(d.getMinutes());
	      break;
	    default:
	      minutos = String(d.getMinutes());
	      break;
	  };

	  return String(dia + ' ' + hora + ':' + minutos);
	}

For example, right now the function returns "Lun 17:5" when it should return "Lun 17:05".

Any comments are welcome!

1
  • Use this: momentjs.com Commented Feb 4, 2015 at 20:08

2 Answers 2

2

Switch statements don't work that way in javascript, instead, it would be:

switch (d.getMinutes()) {
    case 0:
    case 1:
    case 2: // etc...
    case 9:
        minutos = '0' + String(d.getMinutes());
        break;
    default:
        minutos = String(d.getMinutes());
        break;
  };

But definitely try to avoid reinventing the wheel - there are plenty of JS date/time libraries out there that will do this work for you.

Sign up to request clarification or add additional context in comments.

3 Comments

Could you give an example of one such JS library?
Looks like the commenter in your question, Magrangs, suggested a great option - Moment.js. I haven't used that one, but it looks really nice.
moment.js is my go to library for anything date related
1

you should use an if statement instead of a switch statement. something like:

if (d.getMinutes() <= 9) {
    minutos = '0' + String(d.getMinutes());
}
else {
    minutos = String(d.getMinutes());
}

1 Comment

Thanks guys for all your anwsers, I'll definetively try momentjs un the future, right now I'm sticking to this solution as I need to include al my code in a single page .

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.