Search code examples
javascriptstringdatevarsuffix

How to add date original/suffix in custom JQuery?


I have the following Javascript that aim to revise the date format, however I would like to add date original or suffix such as "st", "nd", "rd", "th" to each end date number. For example, let's say our current date is set as 28 April but I want to display date as 28th April.

So if there is a possibility... how can you add this sample coding to the current javascript string?

var nth = function(d) {   if (d > 3 && d < 21) return 'th';   switch (d % 10) {
    case 1:  return "st";
    case 2:  return "nd";
    case 3:  return "rd";
    default: return "th";   } }

Current JS:

  // Blog date
    window.addEventListener('DOMContentLoaded', function () {
    document.querySelectorAll('.waddons-blog-meta').forEach(el => el.textContent = formatDateString(el.textContent))
    }, false);
    function formatDateString(s) {
      var months = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"];
      var arr = s.split('/');
      return arr[1] + " " + months[arr[0] - 1];

      }

Current HTML:

<div class="waddons-blog-meta">3/7/2020 - </div>

Solution

  • Simply you can call the nth function in your code.

    var nth = function (d) {
          if (d > 3 && d < 21) return 'th'; switch (d % 10) {
            case 1: return "st";
            case 2: return "nd";
            case 3: return "rd";
            default: return "th";
          }
        }
    
    window.addEventListener('DOMContentLoaded', function () {
      document.querySelectorAll('.waddons-blog-meta').forEach(el => el.textContent = formatDateString(el.textContent))
    }, false);
    function formatDateString(s) {
      var months = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"];
      var arr = s.split('/');
      return arr[1] + nth(arr[1]) + " " + months[arr[0] - 1];
    }
    

    If you want to superscript the th value, then use following code

    window.addEventListener('DOMContentLoaded', function () {
      document.querySelectorAll('.waddons-blog-meta').forEach(el => el.innerHTML = formatDateString(el.textContent))
    }, false);
    function formatDateString(s) {
      var months = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"];
      var arr = s.split('/');
      return arr[1] + "<sup>" + nth(arr[1]) + "</sup>" + " " + months[arr[0] - 1];
    }