Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert a full date to a short date in javascript?

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.

like image 550
chobo2 Avatar asked Jan 10 '10 01:01

chobo2


1 Answers

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 
like image 118
gnath Avatar answered Oct 05 '22 23:10

gnath