dev1234
dev1234

Reputation: 5716

javascript datetime add zero to single digit values

i have this way of getting tomorrows date.

var tomorrow = date.getDate() + "/" + month + "/" + date.getFullYear();

this returns 2/10/2013 where as i want it to be 02/10/2013 (with the zero for single digits)

This is needed to do a date comparison.

if(02/10/2013==2/10/2013){
dosomething();
}

The above doesnt work due to that issue.

Upvotes: 2

Views: 3623

Answers (4)

Alex Art.
Alex Art.

Reputation: 8781

$.datepicker.formatDate('dd/mm/yy', tomorrow);

You could also use moment.js library for time/date manipulation

Upvotes: 1

RyanB
RyanB

Reputation: 1297

Try this:

if(new Date(2013,2,10).toString() == new Date(2013,02,10).toString()){
    dosomething();
}

Upvotes: 1

Mike
Mike

Reputation: 1231

why you don't use str_pad from phpjs.org this is the code :

  function str_pad (input, pad_length, pad_string, pad_type) {
  // http://kevin.vanzonneveld.net
  // +   original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
  // + namespaced by: Michael White (http://getsprink.com)
  // +      input by: Marco van Oort
  // +   bugfixed by: Brett Zamir (http://brett-zamir.me)
  // *     example 1: str_pad('Kevin van Zonneveld', 30, '-=', 'STR_PAD_LEFT');
  // *     returns 1: '-=-=-=-=-=-Kevin van Zonneveld'
  // *     example 2: str_pad('Kevin van Zonneveld', 30, '-', 'STR_PAD_BOTH');
  // *     returns 2: '------Kevin van Zonneveld-----'
  var half = '',
    pad_to_go;

  var str_pad_repeater = function (s, len) {
    var collect = '',
      i;

    while (collect.length < len) {
      collect += s;
    }
    collect = collect.substr(0, len);

    return collect;
  };

  input += '';
  pad_string = pad_string !== undefined ? pad_string : ' ';

  if (pad_type !== 'STR_PAD_LEFT' && pad_type !== 'STR_PAD_RIGHT' && pad_type !== 'STR_PAD_BOTH') {
    pad_type = 'STR_PAD_RIGHT';
  }
  if ((pad_to_go = pad_length - input.length) > 0) {
    if (pad_type === 'STR_PAD_LEFT') {
      input = str_pad_repeater(pad_string, pad_to_go) + input;
    } else if (pad_type === 'STR_PAD_RIGHT') {
      input = input + str_pad_repeater(pad_string, pad_to_go);
    } else if (pad_type === 'STR_PAD_BOTH') {
      half = str_pad_repeater(pad_string, Math.ceil(pad_to_go / 2));
      input = half + input + half;
      input = input.substr(0, pad_length);
    }
  }

  return input;
}

and apply it to your code:

var tomorrow = str_pad(date.getDate(),2,0,'STR_PAD_LEFT') + "/" + str_pad(month,2,0,'STR_PAD_LEFT') + "/" + date.getFullYear();

Upvotes: 1

Swapnil Patil
Swapnil Patil

Reputation: 979

You can do by

var tomorrow = ('0' + date.getDate()).slice(-2) + "/" +  ('0' + (date.getMonth()+1)).slice(-2) + "/" + date.getFullYear();

Upvotes: 4

Related Questions