gdc3000
gdc3000

Reputation: 23

Trouble working with Date object in Javascript

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!

Upvotes: 0

Views: 48

Answers (2)

indubitablee
indubitablee

Reputation: 8206

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());
}

Upvotes: 1

Joe Enos
Joe Enos

Reputation: 40383

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.

Upvotes: 2

Related Questions