Friday, 28 November 2014

Date tips in Jquery

//Convert String to Date in Jquery
var d = new Date('1991-09-15');
d.getFullYear() => 1991
d.getMonth() + 1 => 9
d.getDate() => 15

The date must be 'yyyy-MM-dd' format.. otherwise in jquery the string date can't be converted into date object.



Current year in jQuery

getFullYear() return the current year.

Current month in jQuery

getMonth() + 1 return the current month. Be careful getMonth() return index of current month, So always use getMonth() + 1 instead of getMonth()

Current day in jQuery

getDate() return the current day.
var currentYear = (new Date).getFullYear();
var currentMonth = (new Date).getMonth() + 1;
var currentDay = (new Date).getDate();

//Convert String to DateTime in jquery

For conversion of DateTime String to date the date format must be like below..
Var d = Date.parse('15/09/1991 05:30 AM')

//Date Comparisions With dates

var d1 = new Date('1991-09-15');
var d2 = new Date('1991-09-14');
(d1 < d2) ? console.log('D2 is bigger') : console.log('D1 is bigger');
Ans : D1 is bigger

//Date Comparisions With datetime

//Convert String dateTime to Date & retruns getTime()
//date like 15/09/1991 05:30 AM
//the below function returns the time function convertDateTime(date){ var O_dateParts = date.split(' '); var hours; if(O_dateParts[2] == "AM" && parseInt(O_dateParts[1].split(':')[0]) == 12) hours = 0; else if(O_dateParts[2] == "AM") hours = O_dateParts[1].split(':')[0]; else if(O_dateParts[2] == "PM") hours = parseInt(O_dateParts[1].split(':')[0]) + 12; return (new Date(O_dateParts[0].split('/')[2],parseInt(O_dateParts[0].split('/')[1])-1,O_dateParts[0].split('/')[0],hours,O_dateParts[1].split(':')[1])).getTime(); }

No comments:

Post a Comment