Formatting dates in JavaScript (handles MySQL dates)


/ Published in: JavaScript
Save to your folder(s)



Copy this code and paste it in your HTML
  1. function format_mysqldate (mysqldate) {
  2. // example mysql date: 2008-01-27 20:41:25
  3. // we need to replace the dashes with slashes
  4. var date = String(mysqldate).replace(/\-/g, '/');
  5. return format_date(date);
  6. }
  7. function format_date (date) {
  8. // date can be in msec or in a format recognized by Date.parse()
  9. var d = new Date(date);
  10.  
  11. var days_of_week = Array('Sun','Mon','Tue','Wed','Thu','Fri','Sat');
  12. var day_of_week = days_of_week[d.getDay()];
  13.  
  14. var year = d.getFullYear();
  15. var months = Array('Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec');
  16. var month = months[d.getMonth()];
  17. var day = d.getDate();
  18.  
  19. var hour = d.getHours();
  20. var minute = d.getMinutes();
  21. var am_pm = 'am';
  22.  
  23. if(hour == 0) {
  24. hour = 12;
  25. } else if (hour == 12) {
  26. am_pm = 'pm';
  27. } else if (hour > 12) {
  28. hour -= 12;
  29. am_pm = 'pm';
  30. }
  31. if(minute < 10) { minute = '0'+minute; }
  32.  
  33. var date_formatted = day_of_week+' '+month+' '+day+' '+year+' '+hour+':'+minute+am_pm;
  34. return date_formatted;
  35. }

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.