4

how to display a date as 2/25/2007 format in javascript, if i have date object

Suresh
  • 38,717
  • 16
  • 62
  • 66

6 Answers6

7
function formatDate(a) //pass date object
{
  return (a.getMonth() + 1) + "/" + a.getDate() + "/" +  a.getFullYear();
}
TheVillageIdiot
  • 40,053
  • 20
  • 133
  • 188
6

This would work:

[date.getMonth() + 1, date.getDay(), date.getFullYear()].join('/')
slikts
  • 8,020
  • 1
  • 27
  • 47
1

Check out moment.js! It's a really powerful little library for working with Dates in JavaScript.

Using moment.js...

var today = moment(new Date());
today.format("M/D/YYYY");                  // "4/11/2012"
today.format("MMMM D, YYYY h:m A");        // outputs "April 11, 2012 12:44 AM"

// in one line...
moment().format("M/D/YYY");                // "4/11/2012"
moment().format("MMMM D, YYYY h:m A");     // outputs "April 11, 2012 12:49 AM"

Another example...

var a = moment([2012, 2, 12, 15, 25, 50, 125]);
a.format("dddd, MMMM Do YYYY, h:mm:ss a"); // "Monday, March 12th 2012, 3:25:50 pm"
a.format("ddd, hA");                       // "Mon, 3PM"

Also, its worth mentioning to checkout date.js. I think the two libraries complement each other.

Hristo
  • 45,559
  • 65
  • 163
  • 230
1

You can try this.

<input type="button" value="display" onclick="display()" />
<input type="text" id="dis" /><br />

<script type="text/javascript">
function display(){
var x="You have clicked";
var d=new Date();
var date=d.getDate();
var month=d.getMonth();
month++;
var year=d.getFullYear();
document.getElementById("dis").value=date+"/"+month+"/"+year;
}
</script>

For more details please visit http://informativejavascript.blogspot.nl/2012/12/date-display.html

kamal
  • 7
  • 2
  • Welcome to Stack Overflow! Thanks for posting your answer! Please be sure to read the [FAQ on Self-Promotion](http://stackoverflow.com/faq#promotion) carefully. Also note that it is *required* that you post a disclaimer every time you link to your own site/product. – Andrew Barber Dec 25 '12 at 16:27
1
(date.getMonth() + 1) + "/" + date.getDay() + "/" + date.getFullYear();
Amarghosh
  • 58,710
  • 11
  • 92
  • 121
  • 2
    getYear() - Returns the year, as a two-digit or a three/four-digit number, depending on the browser. Use getFullYear() instead !! (from w3schools.com) – TheVillageIdiot Oct 08 '09 at 09:02
1

Your best option for all users (internationally) is toLocaleDateString.

var date = new Date("2007-02-25 01:00:00"); // for some reason a time is needed
var dateString = date.toLocaleDateString();
console.log(dateString); // outputs 2/25/2007

Reference: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toLocaleDateString

Luke
  • 18,811
  • 16
  • 99
  • 115