jQuery: formatting MySQL blog dates

In this post I'm going to show you how to format a MySQL blog date into another format. Generally speaking, this kind of formatting is performed before sending the output to a browser by the CMS itself, so this post has only a demonstrative purpose. MySQL has the following format, called DATETIME:

yyyy-mm-dd hh:mm:ss

We want to turn the above format into this:

<span class="day">dd</span>
<span class="month">mm</span>
<span class="year">yyyy</span>

Let's get started with a basic HTML structure like this:

<div class="post">
 <div class="post-title">
  <h2>Lorem ipsum dolor</h2>
  <p>2010-12-28 17:27:28</p>

As you can see, the date contained within the paragraph is in the MySQL format. Now we can add jQuery:

$(document).ready(function() {
 $('div.post-title').each(function() {
  var title = $(this);
  var date = title.find('p').text();
  // MySQL date: yyyy-mm-dd hh:mm:ss
  var rawDate = date.replace(/-+/g, ' ').replace(/:+/g, ' ');
  var dateArr = rawDate.split(' ');
  var reducedArr = dateArr.slice(0, 3);
  var day = reducedArr[2];
  var month = reducedArr[1];
  var year = reducedArr[0];
  var html = '<span class="day">' + day + '</span>' +
             '<span class="month">' + month + '</span>' +
       '<span class="year">' + year + '</span>';

We replace all the '-' and ':' tokens of the paragraph's text with spaces. Then we use those spaces to create an array and we reduce it using the slice() method. So we have all the textual parts we need. Finally, we create the HTML fragment to be inserted in the paragraph itself. You can see the final result here.

Leave a Reply

Note: Only a member of this blog may post a comment.