Reputation: 16491
I am trying to convert my dashed date 2013-12-11 to 2013/12/11 using the following function:
function convertDate(stringdate)
{
// Internet Explorer does not like dashes in dates when converting,
// so lets use a regular expression to get the year, month, and day
var DateRegex = /([^-]*)-([^-]*)-([^-]*)/;
var DateRegexResult = stringdate.match(DateRegex);
var DateResult;
var StringDateResult = "";
// try creating a new date in a format that both Firefox and Internet Explorer understand
try
{
DateResult = new Date(DateRegexResult[2]+"/"+DateRegexResult[3]+"/"+DateRegexResult[1]);
}
// if there is an error, catch it and try to set the date result using a simple conversion
catch(err)
{
DateResult = new Date(stringdate);
}
// format the date properly for viewing
StringDateResult = (DateResult.getMonth()+1)+"/"+(DateResult.getDate()+1)+"/"+(DateResult.getFullYear());
console.log(StringDateResult);
return StringDateResult;
}
As a test I pass var myDate = '2013-12-11'
in and log out before and after the function but the format remains the same? Can anyone suggest where I may be going wrong with this?
Here is a test jsFiddle: http://jsfiddle.net/wbnzt/
Upvotes: 3
Views: 9369
Reputation: 607
myDate.split("-").join("/")
Logic: Split it by dash. Join it by Slash.
Upvotes: 1
Reputation: 10258
Your function is working as expected convertDate(myDate) is returning the / value off the date.
Your problem seems to be your logging
var myDate = '2013-12-11';
console.log('Before', myDate); //2013-12-11
convertDate(myDate);
console.log('After', myDate); //2013-12-11
Your function returns a value so convertDate(myDate) is just returning and doing nothing. And your console log for after is just returning the same date as before.
If you change your console log to
console.log('After', convertDate(myDate)); //2013-12-11
You will get the expected result, or set myDate to the new value
myDate = convertDate(myDate);
console.log('After', myDate); //2013-12-11
Upvotes: 1
Reputation: 6536
I'm not sure if I misunderstand the question; why not just this:
function convertDate(stringdate)
{
stringdate = stringdate.replace(/-/g, "/");
return stringdate;
}
Upvotes: 4
Reputation: 19578
Use String Replace to replace the dashes with slashes.
string.replace(/-/g,"/")
Upvotes: 6