Skip to main content

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

Comments

Popular posts from this blog

Simple Color Picker - a jQuery color picker control

It's been a while since I build this small plugin for jQuery, While browsing through my files I try to see if this plugin still works with the latest version of jQuery which is 1.3.2 and it did. I have updated the sample and change the file names so it is easy to recognize. I also move the downloads to my google site, Download here . Focus on the input box below or click on the box next to the control to show color picker. Basic Sample jQuery(function($) { $("#vtrColorPicker").attachColorPicker(); }); Change Background jQuery(function($) { $("#vtrColorPicker1").attachColorPicker(); $("#vtrColorPicker1").change(function() { $("#content-wrapper").css("background-color",$("#vtrColorPicker1").getValue()); });

dnnAlert and dnnConfirm jQuery Plugin

I like the idea of using jQuery Plugins in DNN for interactive and consistent user interface which is why I digg into using dnnAlert and dnnConfirm plugins, however after a quick look on the documentation I notice the following. For dnnAlert you can't set the title. We are allowed to set the OK button text using okText option but not the dialog title? For dnnConfirm. This is very usefull when you just want a confirmation dialog upon click on your button or link however you can't use it like javascript confirm function or at least I don't know how to use it like below: if(confirm('Question?')){//some code}

Example on how to use dnnConfirm jQuery Plugin

The JS code below will show a dnn confirm dialog upon click on any button with my-Button class.  Pay attention to isButton option on initialization and the isTrigger parameter on button click. //initialization $(".my-Button").dnnConfirm({     text: "Confirm Message",     title: "Confirm",     isButton: true }); //button click handler $(".my-Button").click(function (e, isTrigger) {     if (isTrigger) {         // Your code here     }     return false; });