I want to convert dd/mm/yyyy to mm/dd/yyyy in javascript.
var date = "24/09/1977";
var datearray = date.split("/");
var newdate = datearray[1] + '/' + datearray[0] + '/' + datearray[2];
newdate will contain 09/24/1977. The split method will split the string wherever it finds a "/", so if the date string was "24/9/1977", it would still work and return 9/24/1977.
You can use the following function specified, 1 date and 2 the date separator (optional) The date will be returned in the desired format.
const setFormatDDMMYYYYtoMMDDYYYY = (date, separator = '/') => {
const [day, month, year] = date.split('/');
return month + separator + day + separator + year;
};
var months = new Array("jan", "feb", "mar", "apr", "may", "jun", "jul", "aug", "sep", "oct", "nov", "dec");
var ddSplit = '12/23/2011'.split('/'); //date is mm/dd/yyyy format
alert(ddSplit[1]+'-'+months[ddSplit[0]-1] + '-' + ddSplit[2])
use this function
function dateFormat(existingFormat,neededFormat,existingSeperator,newSeperator,dateValue)
{
var exst = existingFormat.toLowerCase().split(existingSeperator);
var d = dateValue.split(existingSeperator);
d[exst[0]] = d[0]; d[exst[1]]=d[1]; d[exst[2]]=d[2];
var newst = neededFormat.toLowerCase().split(existingSeperator);
newDate = d[newst[0]] +newSeperator+d[newst[1]] +newSeperator+d[newst[2]];
return(newDate);
}
var dd = dateFormat('dd/yy/mm','mm/dd/yy','/','-','30/87/05');//dateFormat(existingFormat,neededFormat,existingSeperator,newSeperator,dateValue)
//use same name for date month and year in both formats
You can use this function for converting any format date(including month date year only) to any format. :)
This is a moment.js version. The library can be found at http://momentjs.com/
//specify the date string and the format it's initially in
var mydate = moment('15/11/2000', 'DD/MM/YYYY');
//format that date into a different format
moment(mydate).format("MM/DD/YYYY");
//outputs 11/15/2000
Try this example where a regular expression is used to find and switch the parts of the string:
var d1 = "03/25/2011";
var d2 = d1.replace(/^(\d{1,2}\/)(\d{1,2}\/)(\d{4})$/,"$2$1$3");
alert("d1:"+d1 +"\n d2:"+d2 )
/*
// OUTPUT
d1: 03/25/2011
d2: 25/03/2011
*/
EDIT:
I noticed that no other answer is using regular expression and I really wonder why... :)