Connor Bishop Connor Bishop - 4 months ago 10
Javascript Question

covert date string to dd/mm/yy in javascript

I want to convert

Tue Jul 12 2016 00:00:00 GMT+0100 (BST)


into

12/07/2016


Say I have d = Tue Jul 12 2016 00:00:00 GMT+0100 (BST). I tried

var a = d.getDate()+"/"+(d.getMonth()+1)+"/"+d.getFullYear();


But then I get 12/7/2016 instead of 12/07/2016

I could do

if(d.getMonth()<10){
var a = d.getDate()+"/0"+(d.getMonth()+1)+"/"+d.getFullYear();


But I don't like that and plus I will have the same problem when the day is less than 10. Whats the best way to get to my desired format. I just need it as a string for display in a view.

Answer

What about this

var month = 7; // july (months are base 0)
var day = 12;
var year = 2016;
var d = new Date(year,month-1,day);

var a = pad(d.getDate(),2)+"/"+pad(d.getMonth()+1,2)+"/"+d.getFullYear();
console.log(a)


function pad(num, size) {
    var s = num+"";
    while (s.length < size) s = "0" + s;
    return s;
}

Used padding function from How to output integers with leading zeros in JavaScript

This is another padding function (i've used a lot)

var month = 7; // july (months are base 0)
var day = 12;
var year = 2016;
var d = new Date(year,month-1,day);

var a = pad(d.getDate(),2)+"/"+pad(d.getMonth()+1,2)+"/"+d.getFullYear();
console.log(a)

/**
 * Returns a zero-padded string of length characters
 * When the number is more than the length, the number is returned 
 * in its full length (longer than the specified length)
 * @param {Number} number The number to be padded
 * @param {Number=2} length
 * @returns {String} the padded String or the number if longer than specified length
 */
function pad(number, length) {
    length = length || 2;
    var missing = length - digits(number);
    if (missing < 0)  return number.toString();
    return Array(missing + 1).join("0") + number.toString();
}

/**
 * Utility function to return the number of digits of a number
 * @param {Number} int the number for which to get the #digits
 * @returns {Number} the number of digits
 */
function digits(int) {
    return Math.floor(Math.log(int) / Math.LN10 + 1);
}