4

Possible Duplicate:
Javascript add leading zeroes to date

It might be a simple question because I am still newbie in JavaScript, assume I have DateTime in ISO format:

 2012-07-07T17:00:00

I would like to format this date to string:

 07.07.2012

I have written a function to format to 7.7.2012 as below:

var formatDate = function (datum) {
    var date = new Date(datum);
    return date.getDate() + '.' + (date.getMonth() + 1) + '.' + date.getFullYear();
};

How can I modify this code to get the result 07.07.2012 instead of 7.7.2012

Community
  • 1
  • 1
cuongle
  • 74,024
  • 28
  • 151
  • 206

3 Answers3

6

This might be helpful.

<script type="text/javascript">

    var date=new Date();
    day=date.getDate();
    month=date.getMonth();
    month=month+1;
    if((String(day)).length==1)
    day='0'+day;
    if((String(month)).length==1)
    month='0'+month;

    dateT=day+ '.' + month + '.' + date.getFullYear();
    //dateT=String(dateT);
    alert(dateT);
</script>
polin
  • 2,745
  • 2
  • 15
  • 20
2

You can also take a look at this

Moment.js

Its the best I found, and it also has a host of other useful functions.

Mandeep Jain
  • 2,304
  • 4
  • 22
  • 38
  • 1
    [date-fns](https://date-fns.org/) is recommended these days (more modular, modern syntax, actively maintained) – Hans Knöchel Jun 07 '20 at 09:27
  • Or [dayjs](https://github.com/iamkun/dayjs) if you want to stay close to the moment API without the huge footprint. – davidenke Jun 10 '20 at 11:44
1

use this handy script. The link provides instructions

http://blog.stevenlevithan.com/archives/date-time-format

75inchpianist
  • 4,112
  • 1
  • 21
  • 39