0

I am trying to split the current date into parts and this is what I am doing

        var today = new Date();

        var currDay = today.getDay();
        var currMonth = today.getMonth();
        var currYear = today.getYear();
        alert(currDay + "/" + currMonth + "/" + currYear)

but with this I get the following result

        0/7/115 (output)

where it should be

        09/07/2015

What can I do to get the required result?

Danish Ali
  • 137
  • 3
  • 19
  • `.getFullYear()` is what you should use instead of `.getYear()`, and you'll have to [pad the numbers with zeros yourself.](http://stackoverflow.com/questions/10073699/pad-a-number-with-leading-zeros-in-javascript) – Pointy Aug 09 '15 at 15:57
  • Thanks @Pointy it worked... – Danish Ali Aug 09 '15 at 16:01
  • possible duplicate of [How to get current date in JavaScript?](http://stackoverflow.com/questions/1531093/how-to-get-current-date-in-javascript) – baao Aug 09 '15 at 16:05

5 Answers5

0

Try

var currYear = today.getFullYear();
K K
  • 16,034
  • 4
  • 25
  • 37
0

Based on the answer from https://stackoverflow.com/a/3605248/2649340:

var today = new Date();

var output   = ('0' + today.getDate()).slice(-2) + '/'
             + ('0' + (today.getMonth()+1)).slice(-2) + '/'
             + today.getFullYear();
Community
  • 1
  • 1
svecon
  • 504
  • 1
  • 5
  • 8
0

Your "today.getDay()" should be "today.getDate()" since .getDay goes from 0-6 (days of the week)

var today = new Date();
var currDay = today.getDate();
var currMonth = today.getMonth();
var currYear = today.getFullYear();
alert(currDay + "/" + currMonth + "/" + currYear);
Kevin P.
  • 401
  • 4
  • 13
0

getDay() gives you the day's number (0-6 for sunday to monday), month starts with 0 for january. This is how to do:

var today = new Date();
var day = today.getDate();
var month = today.getMonth()+1;
var year = today.getFullYear();

if(day<10) {
    day='0'+day;
} 

if(month<10) {
    month='0'+month;
} 

today = month+'/'+day+'/'+year;
alert(today);
baao
  • 62,535
  • 14
  • 113
  • 168
0

you can use moment.js. It has a lot of helpful functions for time and date in JavaScript

hypery2k
  • 1,611
  • 14
  • 19