2

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.

Connor Bishop
  • 921
  • 1
  • 12
  • 21
  • When you say you have `Tue Jul 12 2016 00:00:00 GMT+0100 (BST)` how is that being generated? Does it matter if the date is gathered another way? – JoeL Jul 26 '16 at 14:35
  • Any method is fine. I generated the date with the new Date() method. – Connor Bishop Jul 26 '16 at 14:35
  • 1
    There are hundreds of questions that ask this. Do any of them solve your problem? http://stackoverflow.com/q/11591854/1612146 http://stackoverflow.com/q/12409299/1612146 -- See https://www.google.co.uk/search?q=mm+dd+yyyy+date+javascript+site:stackoverflow.com – George Jul 26 '16 at 14:35
  • How about `("0" + d.getDate()).slice( -2 )` – pishpish Jul 26 '16 at 14:36

5 Answers5

1

var date = new Date();

var dateFormat = getFormatDate(date);
var dateOneLiner = getFormattedDateOneLiner(date);

console.log("DateFormat", dateFormat);
console.log("OneLiner", dateOneLiner);




function getFormatDate(pDate)
{
  var day = pDate.getDate();
  var month = pDate.getMonth() + 1;
  var year = pDate.getFullYear();
  
  if(month < 10)
   month = "0" + month;
  
  if(day < 10)
   day = "0" + day;
    
  return day + "/" + month + "/" + year;
}

function getFormattedDateOneLiner(pDate)
{  
  return (pDate.getDate() < 10 ? "0" + pDate.getDate() : pDate.getDate()) + "/" + ((pDate.getMonth() + 1) < 10 ? "0" + (pDate.getMonth() + 1) : (pDate.getMonth() + 1)) + "/" + pDate.getFullYear();
}
Jorrex
  • 1,503
  • 3
  • 13
  • 32
  • Shoot, didn't see the part where you asked for a smooth way to do this. Well, in any case, this is the full way to do this. For those who stumble upon this matter. – Jorrex Jul 26 '16 at 14:40
  • I suppose its not too messy, thought there might be something already built into java script – Connor Bishop Jul 26 '16 at 14:41
  • That's how I use a format, I did add a one liner. But that's a bit harder to read, but it does exactly the same thing. – Jorrex Jul 26 '16 at 14:48
1

The trick is to add a conditional to check if a day or month is less than 10, and if so to add a 0. This method below is a shorthand version of it but it works. Granted, I have a bit of extra stuff like definitions for yyyy, mm, and dd just to make it a bit clearer where things are coming from. But the portion in the return is what does the magic and you could apply perhaps to your situation.

Date.prototype.yyyymmdd = function() {
  var yyyy = this.getFullYear().toString();
  var mm = (this.getMonth()+1).toString(); // getMonth() is zero-based
  var dd  = this.getDate().toString();
  return (mm[1]?mm:"0"+mm[0]) + "/" + (dd[1]?dd:"0"+dd[0]) + "/" + yyyy; // padding
 };
d = new Date();
document.getElementById("date").innerHTML = d.yyyymmdd();
<span id="date"></span>
JoeL
  • 710
  • 4
  • 18
1

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

You might also want to check http://momentjs.com/ to "Parse, validate, manipulate, and display dates 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) {
    if (length === undefined) {
        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);
}
Community
  • 1
  • 1
raphaëλ
  • 6,393
  • 2
  • 29
  • 35
  • What if *length* is zero? – RobG Jul 28 '16 at 03:17
  • @RobG fixed ;) (for people who wonder what has changed: the idiomatic optional value code (`param = param || default`) does not work `0` (as it is falsy, there are others like `false` with a default of `true` that don't work as expected) – raphaëλ Jul 28 '16 at 06:37
0

You can use a one line like this :

    var a = (d.getDate() < 10? "0"+d.getDate():d.getDate())
     +"/"+   (d.getMonth()+1 <10? ("0"+(d.getMonth()+1)):d.getMonth()+1 )
     +"/"+d.getFullYear();
stevokk
  • 152
  • 9
Jax Teller
  • 1,447
  • 2
  • 15
  • 24
0

Lots of ways to do this. Here are two possible one-liners:

var a = ("0"+d.getDate()).slice(-2)+"/"+("0"+(d.getMonth()+1)).slice(-2)+"/"+d.getFullYear();

var a = ("0"+d.getDate()+"/0"+(d.getMonth()+1)).replace(/\d(\d\d)/g, '$1')+"/"+d.getFullYear();
Tim
  • 1