14

How do I format this date so that the alert displays the date in MM/dd/yyyy format?

<script type="text/javascript">
   var date = new Date();
   alert(date);
</script>
Helen
  • 87,344
  • 17
  • 243
  • 314
ScArcher2
  • 85,501
  • 44
  • 121
  • 160

11 Answers11

31

You prototype a method so you never have to do this irritating task again:

Date.prototype.toFormattedString = function (f)
{
    var nm = this.getMonthName();
    var nd = this.getDayName();
    f = f.replace(/yyyy/g, this.getFullYear());
    f = f.replace(/yy/g, String(this.getFullYear()).substr(2,2));
    f = f.replace(/MMM/g, nm.substr(0,3).toUpperCase());
    f = f.replace(/Mmm/g, nm.substr(0,3));
    f = f.replace(/MM\*/g, nm.toUpperCase());
    f = f.replace(/Mm\*/g, nm);
    f = f.replace(/mm/g, String(this.getMonth()+1).padLeft('0',2));
    f = f.replace(/DDD/g, nd.substr(0,3).toUpperCase());
    f = f.replace(/Ddd/g, nd.substr(0,3));
    f = f.replace(/DD\*/g, nd.toUpperCase());
    f = f.replace(/Dd\*/g, nd);
    f = f.replace(/dd/g, String(this.getDate()).padLeft('0',2));
    f = f.replace(/d\*/g, this.getDate());
    return f;
};

(and yes you could chain those replaces, but it's not here for readability before anyone asks)


As requested, additional prototypes to support the above snippet.

Date.prototype.getMonthName = function ()
{
    return this.toLocaleString().replace(/[^a-z]/gi,'');
};

//n.b. this is sooo not i18n safe :)
Date.prototype.getDayName = function ()
{
    switch(this.getDay())
    {
        case 0: return 'Sunday';
        case 1: return 'Monday';
        case 2: return 'Tuesday';
        case 3: return 'Wednesday';
        case 4: return 'Thursday';
        case 5: return 'Friday';
        case 6: return 'Saturday';
    }
};

String.prototype.padLeft = function (value, size) 
{
    var x = this;
    while (x.length < size) {x = value + x;}
    return x;
};

and usage example:

alert((new Date()).toFormattedString('dd Mmm, yyyy'));
annakata
  • 74,572
  • 17
  • 113
  • 180
  • 5
    This code depends on having prototypes for Date.getMonthName(), Date.getDayName(), and String.padLeft(). This snippet may be more useful to people if you also provided those implementations. – Kevin Ivarsen Jun 12 '09 at 14:04
  • 1
    another great implementation (if you like PHP's date() function) is here: http://jacwright.com/projects/javascript/date_format – david Jun 12 '09 at 14:22
  • 3
    @Kevin - duly provided, though I'd like to note my intention was to suggest "this is how it should be done", more than "please use this code" :) – annakata Jun 12 '09 at 15:11
  • The way that `getMonthName` is parsed, it screws up in some locales resulting in weird outputs like `Mm*` = `WedSep` – Oleg Sep 13 '13 at 00:37
8

You have to get old school on it:

Date.prototype.toMMddyyyy = function() {

    var padNumber = function(number) {

        number = number.toString();

        if (number.length === 1) {
            return "0" + number;
        }
        return number;
    };

    return padNumber(date.getMonth() + 1) + "/" 
         + padNumber(date.getDate()) + "/" + date.getFullYear();
};
Garry Shutler
  • 32,260
  • 12
  • 84
  • 119
4

add Jquery Ui plugin to your page

alert($.datepicker.formatDate('dd M yy', new Date()));
Thulasiram
  • 8,432
  • 8
  • 46
  • 54
2

You rip the .toFormattedString function out of microsofts excellent and now sadly missed atlas library:

Date.prototype.toFormattedString = function (format) {
    var dtf = Sys.CultureInfo.DateTimeFormat;

    if (!format)
        format = "F";

    if (format.length == 1) {
        switch (format) {
            case "d":
                format = dtf.ShortDatePattern;
                break;
            case "D":
                format = dtf.LongDatePattern;
                break;
            case "t":
                format = dtf.ShortTimePattern;
                break;
            case "T":
                format = dtf.LongTimePattern;
                break;
            case "F":
                format = dtf.FullDateTimePattern;
                break;
            case "M": case "m":
                format = dtf.MonthDayPattern;
                break;
            case "s":
                format = dtf.SortableDateTimePattern;
                break;
            case "Y": case "y":
                format = dtf.YearMonthPattern;
                break;
            default:
                throw Error.createError("'" + format + "' is not a valid date format");
        }
    }

    var regex = /dddd|ddd|dd|d|MMMM|MMM|MM|M|yyyy|yy|y|hh|h|HH|H|mm|m|ss|s|tt|t|fff|ff|f|zzz|zz|z/g;

    var ret = "";
    var hour;

    function addLeadingZero(num) {
        if (num < 10) {
            return '0' + num;
        }
        return num.toString();
    }

    function addLeadingZeros(num) {
        if (num < 10) {
            return '00' + num;
        }
        if (num < 100) {
            return '0' + num;
        }
        return num.toString();
    }

    for (; ; ) {

        var index = regex.lastIndex;

        var ar = regex.exec(format);

        ret += format.slice(index, ar ? ar.index : format.length);

        if (!ar) break;

        switch (ar[0]) {
            case "dddd":
                ret += dtf.DayNames[this.getDay()];
                break;
            case "ddd":
                ret += dtf.AbbreviatedDayNames[this.getDay()];
                break;
            case "dd":
                ret += addLeadingZero(this.getDate());
                break;
            case "d":
                ret += this.getDate();
                break;
            case "MMMM":
                ret += dtf.MonthNames[this.getMonth()];
                break;
            case "MMM":
                ret += dtf.AbbreviatedMonthNames[this.getMonth()];
                break;
            case "MM":
                ret += addLeadingZero(this.getMonth() + 1);
                break;
            case "M":
                ret += this.getMonth() + 1;
                break;
            case "yyyy":
                ret += this.getFullYear();
                break;
            case "yy":
                ret += addLeadingZero(this.getFullYear() % 100);
                break;
            case "y":
                ret += this.getFullYear() % 100;
                break;
            case "hh":
                hour = this.getHours() % 12;
                if (hour == 0) hour = 12;
                ret += addLeadingZero(hour);
                break;
            case "h":
                hour = this.getHours() % 12;
                if (hour == 0) hour = 12;
                ret += hour;
                break;
            case "HH":
                ret += addLeadingZero(this.getHours());
                break;
            case "H":
                ret += this.getHours();
                break;
            case "mm":
                ret += addLeadingZero(this.getMinutes());
                break;
            case "m":
                ret += this.getMinutes();
                break;
            case "ss":
                ret += addLeadingZero(this.getSeconds());
                break;
            case "s":
                ret += this.getSeconds();
                break;
            case "tt":
                ret += (this.getHours() < 12) ? dtf.AMDesignator : dtf.PMDesignator;
                break;
            case "t":
                ret += ((this.getHours() < 12) ? dtf.AMDesignator : dtf.PMDesignator).charAt(0);
                break;
            case "f":
                ret += addLeadingZeros(this.getMilliseconds()).charAt(0);
                break;
            case "ff":
                ret += addLeadingZeros(this.getMilliseconds()).substr(0, 2);
                break;
            case "fff":
                ret += addLeadingZeros(this.getMilliseconds());
                break;
            case "z":
                hour = this.getTimezoneOffset() / 60;
                ret += ((hour >= 0) ? '+' : '-') + Math.floor(Math.abs(hour));
                break;
            case "zz":
                hour = this.getTimezoneOffset() / 60;
                ret += ((hour >= 0) ? '+' : '-') + addLeadingZero(Math.floor(Math.abs(hour)));
                break;
            case "zzz":
                hour = this.getTimezoneOffset() / 60;
                ret += ((hour >= 0) ? '+' : '-') + addLeadingZero(Math.floor(Math.abs(hour))) +
                dtf.TimeSeparator + addLeadingZero(Math.abs(this.getTimezoneOffset() % 60));
                break;
            default:
                debug.assert(false);
        }
    }
    return ret;
}
Luan Nico
  • 5,376
  • 2
  • 30
  • 60
sean
  • 21
  • 1
1

YUI also provides support for date formatting, which was covered in a series of recent blog posts:

Walter Rumsby
  • 7,435
  • 5
  • 41
  • 36
1

A simple format would be:

var d = new Date() // Thu Jun 30 2016 12:50:43 GMT-0500 (Central Daylight Time (Mexico))
d.toJSON(); // "2016-06-30T17:50:43.084Z"
gomflo
  • 171
  • 5
  • The simplest pure-javascript answer! For `input type="date"` one can use `d.toJSON().substr(0,10)` and for `input type="time"` one can use `d.toJSON().substr(11,5)` -- provided one wants GMT instead of local time, of course – Matija Nalis Nov 05 '20 at 18:55
1

With a proper library you could internationalize your app for the whole world with just a few lines of code. By default it automatically localizes the date for the browser locale, but you can also define your own patterns:

dojo.date.locale.format(
  new Date(2007,2,23,6,6,6),
  {datePattern: "yyyy-MM-dd", selector: "date"}
);
// yields: "2007-03-23"

From: Formatting dates and times using custom patterns

Maine
  • 1,878
  • 13
  • 10
0

Just another option:

DP_DateExtensions Library

Not saying it's any better than the other options, but I like it (of course I'm not completely unbiased).

Jim Davis
  • 1,230
  • 6
  • 11
0

Try date.js, for example:

<script type="text/javascript">
   alert(new Date().toString('M/d/yyyy'));
</script>
Bao Le
  • 16,643
  • 9
  • 65
  • 68
0

You Could try:

date = new Date().toLocaleDateString().split("/")
date[0].length == 1 ? "0" + date[0] : date[0]
date[1].length == 1 ? "0" + date[1] : date[1]
date = date[0] + "/" + date[1] + "/" + date[2]
Guy de Carufel
  • 466
  • 4
  • 8
0

2017 year answer: use moment.js

Vadim
  • 1,125
  • 8
  • 18