0

I need a bit of help as my Java script knowledge is poor. I've dealt mainly with HTML and PHP in the past. I need to make a date form that adds a number to a specified date, which I've had some help with and it works. The only think I need to change is the format the date comes out in. At the moment it's out put in the format 'Fri, 02 Jan 2015 00:00:00 GMT' Where as I would quite like it to come out at 02/01/2015

Thanks in advance for your help. I've searched this over and over, but can't find anything that works with my code!

HTML

<input type="text" id="myStartDate" value="01/01/2015">
<select id="myDays">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
<option value="5">5</option>
<option value="6">6</option>
<option value="7">7</option>

Javascript

var inputElement = document.getElementById('myStartDate'),
selectElement = document.getElementById('myDays'),
resultElement = document.getElementById('myResult');

function updateResultElement() {
var parts = inputElement.value.split('/'),
    dateObject;

parts[1] -= 1;
parts.reverse();
dateObject = new Date(Date.UTC.apply(undefined, parts));
dateObject.setUTCDate(dateObject.getUTCDate() + Number(selectElement.value));
resultElement.textContent = dateObject.toUTCString();
}

inputElement.addEventListener('change', updateResultElement, false);
selectElement.addEventListener('change', updateResultElement, false);
updateResultElement();
WillMaddicott
  • 512
  • 6
  • 20
  • 1
    Use the `Date.*` methods here to create the format you want: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date#Methods_2 – Ian Mar 17 '14 at 13:23
  • If you're open to using a third party lib, I would definitely recommend momentJS for dealing with dates in JavaScript - very easy to use and a well documented API. – tymeJV Mar 17 '14 at 13:25
  • possible duplicate of [Where can I find documentation on formatting a date in JavaScript](http://stackoverflow.com/questions/1056728/where-can-i-find-documentation-on-formatting-a-date-in-javascript) – Xotic750 Mar 17 '14 at 15:56

1 Answers1

-1

I'd use the moment library, which has extensive support for date and time formatting.

You should be able to use it in your program as follows:

dateObject = new Date(Date.UTC.apply(undefined, parts));
dateObject.setUTCDate(dateObject.getUTCDate() + Number(selectElement.value));
resultElement.textContent = moment(dateObject).format('DD/MM/YYYY');
aknuds1
  • 65,625
  • 67
  • 195
  • 317