83

I have a date like this Monday, January 9, 2010

I now want to convert it to

1/9/2010 mm/dd/yyyy

I tried to do this

    var startDate = "Monday, January 9, 2010";
    var convertedStartDate = new Date(startDate);
    var month = convertedStartDate.getMonth() + 1
    var day = convertedStartDate.getDay();
    var year = convertedStartDate.getFullYear();
    var shortStartDate = month + "/" + day + "/" + year;

However it must be thinking the date is in a different format since day returns 1 instead of 9.

rstackhouse
  • 2,238
  • 24
  • 28
chobo2
  • 83,322
  • 195
  • 530
  • 832

11 Answers11

74

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
gnath
  • 796
  • 5
  • 8
58

Built-in toLocaleDateString() does the job, but it will remove the leading 0s for the day and month, so we will get something like "1/9/1970", which is not perfect in my opinion. To get a proper format MM/DD/YYYY we can use something like:

new Date(dateString).toLocaleDateString('en-US', {
  day: '2-digit',
  month: '2-digit',
  year: 'numeric',
})

Alternative: We can get similar behavior using Intl.DateTimeFormat which has decent browser support. Similar to toLocaleDateString(), we can pass an object with options:

const date = new Date('Dec 2, 2021') // Thu Dec 16 2021 15:49:39 GMT-0600
const options = {
  day: '2-digit',
  month: '2-digit',
  year: 'numeric',
}
new Intl.DateTimeFormat('en-US', options).format(date) // '12/02/2021'
Constantin
  • 3,655
  • 1
  • 14
  • 23
  • Works perfect! Thanks for sharing. – Devner Feb 23 '20 at 03:16
  • 5
    Not sure why I'm getting downvotes since this is built-in functionality in JS. I don't understand why someone would prefer using external libraries instead of built in features. – Constantin Apr 29 '20 at 20:59
  • I am with you on this. – Devner May 11 '20 at 17:40
  • 1
    How can you use the local datetime string with those options? There isn't an overload for just options and also named parameters doesn't seem to work? – scottdavidwalker Jan 06 '21 at 13:49
  • 1
    The syntax is `dateObj.toLocaleDateString([locales[, options]])`. You can find all the options here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toLocaleDateString – Constantin Jan 07 '21 at 06:27
56

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)

Daniel Szabo
  • 7,181
  • 6
  • 48
  • 65
Roland Bouman
  • 31,125
  • 6
  • 66
  • 67
  • Cool that worked. But how can I set it to always do the mm/dd/yyyy since I always want this in that date format no matter what the client set. Like I know I am printing it in the format I want but I am not sure if how it would react to the conversion if it would try to put it in the client format. – chobo2 Jan 10 '10 at 01:28
  • I am still not sure if I need to be concerned about other date formats. Maybe I have to post a new question. – chobo2 Jan 10 '10 at 01:40
  • `Date` is just a class for representing date/time values. It has a number of methods that return a string representation, but your desired format is simply not there. The format you created is not a `Date` object: it's a string, you just created it with data coming out of the `Date` object. You can try to add your own formatting method to the prototype of the `Date` object. I'll edit my answer to show how. – Roland Bouman Jan 10 '10 at 01:44
  • @Cory Mawhorter "Don't forget": I didn't. I wrote: "but getMonth() from 0..11". Maybe you shouldn't forget to read before you comment. "Don't link to w3schools!" < why not? They explain these points really well. – Roland Bouman Jul 10 '12 at 00:40
  • 7
    Note that you'll want to do `return (this.getMonth() + 1) + "/" + this.getDate() + "/" + this.getFullYear();` if you want the month to be correct (since, as Roland mentioned, `getMonth()` returns 0..11) – snumpy Jun 13 '13 at 15:04
8
var d = new Date("Wed Mar 25 2015 05:30:00 GMT+0530 (India Standard Time)"); 
document.getElementById("demo").innerHTML = d.toLocaleDateString();
Suraj Rao
  • 29,388
  • 11
  • 94
  • 103
Abilash Raghu
  • 383
  • 3
  • 8
  • 1
    While this code may answer the question, it lacks explanation. Please consider adding text to explain what it does, and why it answers the question posed. – Nelewout Aug 18 '18 at 09:11
  • Code does the trick, but as @N.Wouda states, it would be better with some sort of explanation. – Demonic218 Dec 18 '18 at 06:53
3

date.toLocaleDateString('en-US') works great. Here's some more information on it: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toLocaleDateString

TrevorBrooks
  • 3,590
  • 3
  • 31
  • 53
1

I wanted the date to be shown in the type='time' field.

The normal conversion skips the zeros and the form field does not show the value and puts forth an error in the console saying the format needs to be yyyy-mm-dd.

Hence I added a small statement (check)?(true):(false) as follows:

makeShortDate=(date)=>{
yy=date.getFullYear()
mm=date.getMonth()
dd=date.getDate()
shortDate=`${yy}-${(mm<10)?0:''}${mm+1}-${(dd<10)?0:''}${dd}`;
return shortDate;
}
metvsk
  • 189
  • 2
  • 4
1

Although this question posted long long time ago, the proper way to do this is:

Intl.DateTimeFormat("en").format(new Date())

Any way, the Intl (international) object has many options you can pass to like to enforce tow digits etc. You all can look at it here

Itay Merchav
  • 954
  • 8
  • 8
0

I think this is a shorter method to access the date in DD/MM/YYYY format:

console.log(new Intl.DateTimeFormat(['ban', 'id']).format(new Date()));

Even you can get only part of a day like "Afternoon, morning, night, etc.."

-2

I was able to do that with :

var dateTest = new Date("04/04/2013");
dateTest.toLocaleString().substring(0,dateTest.toLocaleString().indexOf(' '))

the 04/04/2013 is just for testing, replace with your Date Object.

a.boussema
  • 1,096
  • 11
  • 19
  • 1
    This was Good for a quick and dirty fix, always loved one liners: For current date! (new Date()).toLocaleString().substring(0,(new Date()).toLocaleString().indexOf(' ')) – JDuarteDJ Dec 17 '15 at 14:13
-2

You could do this pretty easily with my date-shortcode package:

const dateShortcode = require('date-shortcode')

var startDate = 'Monday, January 9, 2010'
dateShortcode.parse('{M/D/YYYY}', startDate)
//=> '1/9/2010'
Kodie Grantham
  • 1,963
  • 2
  • 17
  • 27
-10

Try this:

new Date().toLocaleFormat("%x");
animuson
  • 53,861
  • 28
  • 137
  • 147
user838708
  • 15
  • 2
  • 1
    This is not a standard. According to [MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toLocaleFormat): _This feature is non-standard and is not on a standards track. Do not use it on production sites facing the Web: it will not work for every user. There may also be large incompatibilities between implementations and the behavior may change in the future._ – Josh Dec 22 '13 at 07:39
  • toLocaleString and toLocaleFormat are now obsolete and perhaps even deprecated – Brian Ogden Mar 07 '14 at 04:02