Skip to content

Instantly share code, notes, and snippets.

@timrwood
Created February 8, 2012 16:50
Show Gist options
  • Select an option

  • Save timrwood/1771023 to your computer and use it in GitHub Desktop.

Select an option

Save timrwood/1771023 to your computer and use it in GitHub Desktop.
Moment calendar without time plugin
(function(){
var oldcal = moment.calendar;
var newcal = {
sameDay : '[Today]',
nextDay : '[Tomorrow]',
nextWeek : 'dddd',
lastDay : '[Yesterday]',
lastWeek : '[last] dddd',
sameElse : 'L'
};
moment.fn.oldcalendar = moment.fn.calendar;
moment.fn.calendar = function(withoutTime) {
if (withoutTime) {
moment.calendar = newcal;
} else {
moment.calendar = oldcal;
}
return this.oldcalendar();
}
})()
@timrwood

timrwood commented Feb 8, 2012

Copy link
Copy Markdown
Author

See example here: http://jsfiddle.net/nawxZ/

@Ahrengot

Copy link
Copy Markdown

Nice! Another way, if you only need this functionality once or twice in your app, is to simply cut off everything after the first space like so: momentObj.calendar().match("/\w+/"); which will turn Tuesday at 3:45pm into Tuesday

@colllin

colllin commented Sep 27, 2013

Copy link
Copy Markdown

@Ahrengot Unfortunately that will break dates from last week... like "Last Friday at 2:30pm". Works great if you know your dates are in the future though.

@anri-asaturov

Copy link
Copy Markdown

It no longer works with current moment.js
Had to update it this way: https://gist.github.com/anri82/10013485

@mahfuzak08

Copy link
Copy Markdown

It works perfectly.
(moment(time).calendar().split(" at"))[0]

@carmenchapa

Copy link
Copy Markdown

Also
moment().calendar().substring(0, moment().calendar().indexOf(' at'))
More verbose, but doesn't create an unnecessary array

@drumfish

Copy link
Copy Markdown

Also
moment().calendar().substring(0, moment().calendar().indexOf(' at'))
More verbose, but doesn't create an unnecessary array

this approach doesn't work and return empty string "", if moment doesn't contain " at" this is all "sameElse" dates.

default:
moment().calendar(null, {
sameDay: '[Today]',
nextDay: '[Tomorrow]',
nextWeek: 'dddd',
lastDay: '[Yesterday]',
lastWeek: '[Last] dddd',
sameElse: 'DD/MM/YYYY'
});

+1 to the
(moment(time).calendar().split(" at"))[0]

thanks

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment