Monday, December 8, 2014

Format date and time using Moment.js

The javascript function below will format a given datetime object like facebook ish using momentjs.

function formatDateTime(dte, format) {
    var diff = moment().diff(moment(dte), 'days');
    if (diff == 0) {
        return moment(dte).fromNow();
    else if (diff == 1) {
        return moment(dte).calendar();
    else {
        if (format) {
            return moment(dte).format(format);
        else {
            return moment(dte).format("MMM DD, YYYY hA");

The return value will depend on the datetime pass to the function:

If today
"a few seconds ago" or "13 minutes" ago or "an hour ago"

If yesterday
"Yesterday at 5:15 PM"

If the second parameter is pass it will use it base on momentjs formating

Everything else
Oct 16, 2014 1PM