Nice formatted dates in Javascript.


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

Example: April 5th, 2011


Copy this code and paste it in your HTML
  1. var month_names = new Array('January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'),
  2. now = new Date(),
  3. dayNum = now.getDate(),
  4. dayNum_str = dayNum.toString(),
  5. dayNum_strlen = dayNum_str.length,
  6. dayNum_lastDigit = dayNum_str.substring(dayNum_strlen-1),
  7. dayNum_isTeens = null,
  8. sup = '',
  9. thisMonth = now.getMonth(),
  10. thisYear = now.getFullYear();
  11.  
  12. if (dayNum > 10 && dayNum < 14) {
  13. dayNum_isTeens = true;
  14. }
  15. if (!dayNum_isTeens) {
  16. if (dayNum_lastDigit == 1) {
  17. sup = 'st';
  18. }
  19. else if (dayNum_lastDigit == 2) {
  20. sup = 'nd';
  21. }
  22. else if (dayNum_lastDigit == 3) {
  23. sup = 'rd';
  24. }
  25. }
  26. else {
  27. sup = 'th';
  28. }
  29. var date = ''+ month_names[thisMonth] + ' ' + dayNum + '<sup>' + sup + '</sup>, ' + thisYear;
  30.  
  31. document.write(date);

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.