We Recommend

Pro JavaScript Techniques Pro JavaScript Techniques
Pro JavaScript Techniques is the ultimate JavaScript book for the modern web developer. It provides everything you need to know about modern JavaScript, and shows what JavaScript can do for your web sites. This book doesn't waste any time looking at things you already know, like basic syntax and structures.


Posted By

penguin999 on 02/02/08


Tagged

mysql javascript date format dates formatting


Versions (?)


Who likes this?

1 person has marked this snippet as a favorite

jamesming


Formatting dates in JavaScript (handles MySQL dates)


Published in: JavaScript 


  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 

You need to login to post a comment.