Skip to content

Instantly share code, notes, and snippets.

@jakerb
Last active December 11, 2015 11:12
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jakerb/95288471b5f8fd1e4e45 to your computer and use it in GitHub Desktop.
Save jakerb/95288471b5f8fd1e4e45 to your computer and use it in GitHub Desktop.
Date formatting in jQuery.

jDate

Easily format and return time and date in jQuery.


Formatted Date

To get the date in a DD-MM-YYYY or MM-DD-YYYY format you can use the formatDate function where you can set the separator, use:

jDate.formatDate('-'); //"10-12-2015" jDate.formatDate('-', 'us'); //"12-10-2015" jDate.formatDate('*', 'us'); //"1212015"

Get Time

This will return an object or string with the time of jDate init and timezone.

jDate.getTime(); //"11:07:58" jDate.getTime(true)//Object {time: "11:07:58", timezone: "GMT+0000"}

Get Month

This will return an object with the month name and month integer.

jDate.month(); //Object {month: "Dec", int: 12}

Get Day

This will return an object with the Week day name and day in the month.

jDate.day(); //Object {day: "Fri", int: 11}

To get the Week day as an integer, simply do:

jDate.toNumber(jDate.day().day) //5

var date;
var jDate = {
init:function() {
var that = this;
date = new Date().toString();
date = date.split(' ');
},
month:function() {
var that = this;
return {month: date[1], int: that.toNumber(date[1])};
},
day:function() {
var that = this;
return {day: date[0], int: parseInt(date[2])};
},
formatDate:function(delim, format) {
var that = this;
var strDate = that.toNumber(date[2]) + delim + that.toNumber(date[1]) + delim + date[3];
if(format == "us") {
strDate = that.toNumber(date[1]) + delim + that.toNumber(date[2]) + delim + date[3];
}
return strDate;
},
getTime:function(timezone) {
if(timezone) {
return {time: date[4], timezone: date[5]};
} else {
return date[4];
}
},
toNumber:function(day) {
switch(day) {
case 'Mon':
case 'Jan':
return 1;
break;
case 'Tue':
case 'Feb':
return 2;
break;
case 'Wed':
case 'Mar':
return 3;
break;
case 'Thu':
case 'Apr':
return 4;
break;
case 'Fri':
case 'May':
return 5;
break;
case 'Sat':
case 'Jun':
return 6;
break;
case 'Sun':
case 'Jul':
return 7;
break;
case 'Aug':
return 8;
break;
case 'Sep':
return 9;
break;
case 'Oct':
return 10;
break;
case 'Nov':
return 11;
break;
case 'Dec':
return 12;
break;
default:
return 1;
break;
}
}
};
jDate.init();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment