views:

1082

answers:

4

Hi all, I am trying to create a function on javascript to bring the date from my database in format (yyyy-mm-dd) and display it on the page as (dd/mm/yy).

I would appreciate any help.

Thanks.

PD: Let me know if you need more clarification.

+2  A: 

Use functions getDateFromFormat() and formatDate() from this source: http://mattkruse.com/javascript/date/source.html
Examples are also there

alemjerus
+1 a good idea if you want to parse a range of date formats.
Andy E
+1  A: 

Easiest way assuming you're not bothered about the function being dynamic:

function reformatDate(dateStr)
{
  dArr = dateStr.split("-");  // ex input "2010-01-18"
  return dArr[2]+ "/" +dArr[1]+ "/" +dArr[0].substring(2); //ex out: "18-01-10"
}
Andy E
+1  A: 

If you're sure that the date that comes from the server is valid, a simple RegExp can help you to change the format:

function formatDate (input) {
  var datePart = input.match(/\d+/g),
  year = datePart[0].substring(2), // get only two digits
  month = datePart[1], day = datePart[2];

  return day+'/'+month+'/'+year;
}

formatDate ('2010/01/18'); // "18/01/10"
CMS
A: 

You may also want to look into using date.js:

http://www.datejs.com

To futureproof your application, you may want to return time in a UTC timestamp and format with JavaScript. This'll allow you to support different formats for different countries (in the U.S., we are most familiar with DD-MM-YYYY, or instance) as well as timezones.

Ikai Lan