How to convert a full date to a short date in javascript?
Here you go:
(new Date()).toLocaleDateString('en-US');
That's it !!
you can use it on any date object
let's say.. you have an object called "currentDate"
var currentDate = new Date(); //use your date here
currentDate.toLocaleDateString('en-US'); // "en-US" gives date in US Format - mm/dd/yy
(or)
If you want it in local format then
currentDate.toLocaleDateString(); // gives date in local Format
The getDay()
method returns a number to indicate the day in week (0=Sun, 1=Mon, ... 6=Sat). Use getDate()
to return a number for the day in month:
var day = convertedStartDate.getDate();
If you like, you can try to add a custom format function to the prototype of the Date
object:
Date.prototype.formatMMDDYYYY = function(){
return (this.getMonth() + 1) +
"/" + this.getDate() +
"/" + this.getFullYear();
}
After doing this, you can call formatMMDDYYY()
on any instance of the Date
object. Of course, this is just a very specific example, and if you really need it, you can write a generic formatting function that would do this based on a formatting string, kinda like java's SimpleDateeFormat (http://java.sun.com/j2se/1.4.2/docs/api/java/text/SimpleDateFormat.html)
(tangent: the Date
object always confuses me... getYear()
vs getFullYear()
, getDate()
vs getDay()
, getDate()
ranges from 1..31, but getMonth()
from 0..11
It's a mess, and I always need to take a peek. http://www.w3schools.com/jsref/jsref_obj_date.asp)