Get date using javascript in this format [MM/DD/YY]
Asked Answered
C

3

10


how can I get the date in this format [mm/dd/yy] using javascript. I am struggling to get the 'year' to a 2 digit figure as opposed to the full 4 digits.

Thanks!

Cystic answered 1/11, 2012 at 19:22 Comment(3)
Please show what you've tried.Glorification
Show us the code you already haveCampion
possible duplicate of Formatting a date in JavaScriptMoonlit
S
12

Try this:

HTML

<div id="output"></div>

JS

(function () {
    // Get current date
    var date = new Date();

    // Format day/month/year to two digits
    var formattedDate = ('0' + date.getDate()).slice(-2);
    var formattedMonth = ('0' + (date.getMonth() + 1)).slice(-2);
    var formattedYear = date.getFullYear().toString().substr(2,2);

    // Combine and format date string
    var dateString = formattedMonth + '/' + formattedDate + '/' + formattedYear;

    // Reference output DIV
    var output = document.querySelector('#output');

    // Output dateString
    output.innerHTML = dateString;
})();

Fiddle: http://jsfiddle.net/kboucher/4mLe1Lrd/

Sterigma answered 1/11, 2012 at 19:29 Comment(1)
The dates and months could come out single digit.Vibrio
V
15
var date = new Date();
var datestring = ("0" + (date.getMonth() + 1).toString()).substr(-2) + "/" + ("0" + date.getDate().toString()).substr(-2)  + "/" + (date.getFullYear().toString()).substr(2);

This guarantees 2 digit dates and months.

Vibrio answered 1/11, 2012 at 19:25 Comment(4)
I think you need a + 1 on the getMonth()Andreasandree
@AdamRackis Yeah I edited a few seconds ago, just realised I put the increment on the date.Vibrio
It's incorrect, getYear() will return year in three digits for year passed 2000, see tinker.io/a7188Sharpe
@Sharpe Updated, fixed the month and date too.Vibrio
S
12

Try this:

HTML

<div id="output"></div>

JS

(function () {
    // Get current date
    var date = new Date();

    // Format day/month/year to two digits
    var formattedDate = ('0' + date.getDate()).slice(-2);
    var formattedMonth = ('0' + (date.getMonth() + 1)).slice(-2);
    var formattedYear = date.getFullYear().toString().substr(2,2);

    // Combine and format date string
    var dateString = formattedMonth + '/' + formattedDate + '/' + formattedYear;

    // Reference output DIV
    var output = document.querySelector('#output');

    // Output dateString
    output.innerHTML = dateString;
})();

Fiddle: http://jsfiddle.net/kboucher/4mLe1Lrd/

Sterigma answered 1/11, 2012 at 19:29 Comment(1)
The dates and months could come out single digit.Vibrio
C
1

How About this for the year

String(new Date().getFullYear()).substr(2)

And since you need your Month from 01 through 12 do this

var d = new Date("2013/8/3"); 
(d.getMonth() < 10 ? "0" : "") + (d.getMonth() + 1)

Do the same thing for days, Minutes and seconds

Working Demo

Clarkia answered 23/11, 2013 at 1:19 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.