Saturday, 18 April 2015

JavaScript DateTime Handling

Most of this information is available on the net. I have compiled into a single document for easy reading.

JavaScript code is after the descriptions.

Month List Array

var monthList = datetime.getMonthsList;
Array list has following properties
  • Month: month index
  • Month2Digit: month 2 digit index
  • Days: days in the month
  • Name: month name

 

 Days List Array

var daysList = datetime.getDaysList;
Array list has following properties
  • Name: day name
  • Day: index
  • Day2Digit: index 2 digit

 

Get Month

returns 2 digit month
var monthDigit1 = datetime.getMonth(currentDate); OR
var monthDigit2 = datetime.getMonth();

 

Get Month Name

returns month name
var month1 = datetime.getMonthName(currentDate); OR
var month2 = datetime.getMonthName();

 

Get Day

returns 2 digit daya
var day1 = datetime.getDay(currentDate); OR
var day2 = datetime.getDay();

 

Get Day Name

returns days name
var day1 = datetime.getDayName(currentDate); OR
var day2 = datetime.getDayName();

 

Get 4 digit year

var year = datetime.getYear(currentDate); OR
var year = datetime.getYear();

 

Get 2 digit year

var year = datetime.get2DigitYear(currentDate); OR
var year = datetime.get2DigitYear();

 

Get Date

var date1 = datetime.getDate(currentDate); OR
var date2 = datetime.getDate();

 

Get date with day as 1

var date1 = datetime.getDateWithFirstofMonth(currentDate); OR
var date2 = datetime.getDateWithFirstofMonth();

 

Get 2 digit hour

var hour1 = datetime.getHour(currentDate); OR
var hour2 = datetime.getHour();

 

Get 2 digit minute

var min1 = datetime.getMinute(currentDate); OR
var min2 = datetime.getMinute();

 

Get 2 digit second

var sec1 = datetime.getSecond(currentDate); OR
var sec2 = datetime.getSecond();

 

Get time type (AM/PM)

var type1 = datetime.getTimeType(currentDate); OR
var type2 = datetime.getTimeType();

 

Get current time

var time = datetime.currentTime();

 

Get time list Array

var list1 = datetime.getTimeList(intervalInMinutes); OR
var list2 = datetime.getTimeList(); since we are not passing an interval, it will be 15 mins by default
Object has following properties:
  • Hour: hours list
  • Minute: minutes list
  • Type: array list of AM and PM

 

Subtract days from date

var date = datetime.subtractDaysFromDate(date, days);

 

Add days to date

var date = datetime.addDaysToDate(date, days);

 

Validate Date

var isDate = datetime.isDate(date); //pass date as MM/DD/YYYY
returns true/false

 

Is date 1 greater than date 2

var isGreater = datetime.isDate1GreaterThanDate2(date1,date2);

 

Is date 1 greater than or equal to date 2

var isGreaterEqualTo = datetime.isDate1GreaterThanOrEqualToDate2(date1,date2);

 

Is Leap Year

var isLeapYear = datetime.isLeapYear(year); //pass 4 digit year

 

February Max Days

var days1 = datetime.februaryMaxDays(date); OR
var days2 = datetime.februaryMaxDays();
returns 28 or 29.

DateTime.js

 var DateTimeUtilities = {
    getMonthsList: function (d) { //date is used for finding the max day for february 28 or 29, if checking against current year then do not pass
        return [
            { Month: 1, Month2Digit: '01', Days: 31, Name: 'January' },
            { Month: 2, Month2Digit: '02', Days: DateTimeUtilities.februaryMaxDays(d), Name: 'February' },
            { Month: 3, Month2Digit: '03', Days: 31, Name: 'March' },
            { Month: 4, Month2Digit: '04', Days: 30, Name: 'April' },
            { Month: 5, Month2Digit: '05', Days: 31, Name: 'May' },
            { Month: 6, Month2Digit: '06', Days: 30, Name: 'June' },
            { Month: 7, Month2Digit: '07', Days: 31, Name: 'July' },
            { Month: 8, Month2Digit: '08', Days: 31, Name: 'August' },
            { Month: 9, Month2Digit: '09', Days: 30, Name: 'September' },
            { Month: 10, Month2Digit: '10', Days: 31, Name: 'October' },
            { Month: 11, Month2Digit: '11', Days: 30, Name: 'November' },
            { Month: 12, Month2Digit: '12', Days: 31, Name: 'December' }
        ];
    },
    getDaysList: [
        { Name: 'Sunday', Day: 0, Day2Digit: '00' },
        { Name: 'Monday', Day: 1, Day2Digit: '01' },
        { Name: 'Tuesday', Day: 2, Day2Digit: '02' },
        { Name: 'Wednesday', Day: 3, Day2Digit: '03' },
        { Name: 'Thursday', Day: 4, Day2Digit: '04' },
        { Name: 'Friday', Day: 5, Day2Digit: '05' },
        { Name: 'Saturday', Day: 6, Day2Digit: '06' }
    ],
    getMonth: function (d) { //d is optional
        if (d == null || d == 'undefined') d = new Date;
        else d = new Date(d);
        var month = String(d.getMonth() + 1);
        if (month.length == 1) month = "0" + month;
        return month;
    },
    getMonthName: function (d) { //d is optional
        var month = DateTimeUtilities.getMonth();
        var monthList = DateTimeUtilities.getMonthsList();
        var monthName = '';
        for (var i = 0; i < monthList.length; i++) {
            if (month == String(monthList[i].Month) || month == monthList[i].Month2Digit) {
                monthName = monthList[i].Name;
                break;
            }
        }
        return monthName;
    },
    getDay: function (d) { //d is optional
        if (d == null || d == 'undefined') d = new Date;
        else d = new Date(d);
        var day = String(d.getDate());
        if (day.length == 1) day = "0" + day;
        return day;
    },
    getDayName: function (d) { //d is optional
        if (d == null || d == 'undefined') d = new Date;
        else d = new Date(d);
        var day = d.getDay();
        var dayName = '';
        for (var i = 0; i < DateTimeUtilities.getDaysList.length; i++) {
            if (day == String(DateTimeUtilities.getDaysList[i].Day) || day == DateTimeUtilities.getDaysList[i].Day2Digit) {
                dayName = DateTimeUtilities.getDaysList[i].Name;
                break;
            }
        }
        return dayName;
    },
    getYear: function (d) { //d is optional
        if (d == null || d == 'undefined') d = new Date;
        else d = new Date(d);
        return d.getFullYear();
    },
    get2DigitYear: function (year) {
        year = String(year);
        if (year != '' && year.length == 4)
            year = year.substring(year.length, 2);
        return year;
    },
    getDate: function (d) { //d is optional
        var month = String(DateTimeUtilities.getMonth(d));
        var day = String(DateTimeUtilities.getDay(d));
        var year = String(DateTimeUtilities.getYear(d));

        if (day.length == 1) day = "0" + day;
        if (month.length == 1) month = "0" + month;

        return month + "/" + day + "/" + year;
    },
    getDateWithFirstofMonth: function (d) { //d is optional
        var month = String(DateTimeUtilities.getMonth(d));
        if (month.length == 1) month = "0" + month;
        return month + "/01/" + DateTimeUtilities.getYear(d);
    },
    getHour: function (d) { //d is optional
        if (d == null || d == 'undefined') d = new Date();
        else d = new Date(d);
        var nHour = d.getHours();
        if (nHour == 0)
            nHour = 12;
        else if (nHour > 12)
            nHour = nHour - 12;
        return nHour;
    },
    getMinute: function (d) { //d is optional
        if (d == null || d == 'undefined') d = new Date();
        else d = new Date(d);
        return d.getMinutes();
    },
    getSecond: function (d) { //d is optional
        if (d == null || d == 'undefined') d = new Date();
        else d = new Date(d);
        return d.getSeconds();
    },
    getTimeType: function (d) {//d is optional
        if (d == null || d == 'undefined') d = new Date();
        else d = new Date(d);
        var nHour = d.getHours();
        var cType = "AM";
        if (nHour >= 12)
            cType = "PM";
        return cType;
    },
    currentTime: function () {
        var hour = String(DateTimeUtilities.getHour());
        var min = String(DateTimeUtilities.getMinute());
        var sec = String(DateTimeUtilities.getSecond());

        if (hour.length == 1) hour = "0" + hour;
        if (min.length == 1) min = "0" + min;
        if (sec.length == 1) sec = "0" + sec;

        return hour + ':' + min + ':' + sec + ' ' + DateTimeUtilities.getTimeType();
    },
    getTimeList: function (minuteInterval) { //default is 15 minute interval
        if (minuteInterval == null || minuteInterval == 'undefined') minuteInterval = 15;
        var index = 0;
        var arrHr = new Array();
        for (var i = 1; i <= 12; i++) {
            arrHr[index] = i;
            index++;
        }
        index = 0;
        var arrMin = new Array();
        var iMin;
        for (i = 0; i <= 59; i++) {
            iMin = '' + i;
            if (iMin.length == 1) iMin = '0' + i;
            arrMin[index] = iMin;
            if (minuteInterval != 0)
                i += minuteInterval - 1;
            index++;
        }
        //return object with 3 members
        var obj = {
            Hour: arrHr,
            Minute: arrMin,
            Type: ['AM', 'PM']
        };
        return obj;
    },
    subtractDaysFromDate: function (d, days) {
        d = new Date(d);
        d.setDate(d.getDate() - days);
        return DateTimeUtilities.getDate(d);
    },
    addDaysToDate: function (d, days) {
        d = new Date(d);
        d.setDate(d.getDate() + days);
        return DateTimeUtilities.getDate(d);
    },
    isDate1GreaterThanDate2: function (date1, date2) {
        var blnReturn = false;
        if (DateTimeUtilities.isDate(date1) && DateTimeUtilities.isDate(date2)) {
            date1 = new Date(date1);
            date2 = new Date(date2);
            if (date1 > date2)
                blnReturn = true;
        }
        return blnReturn;
    },
    isDate1GreaterThanOrEqualToDate2: function (date1, date2) {
        var blnReturn = false;
        if (DateTimeUtilities.isDate(date1) && DateTimeUtilities.isDate(date2)) {
            date1 = new Date(date1);
            date2 = new Date(date2);
            if (date1 >= date2)
                blnReturn = true;
        }
        return blnReturn;
    },
    isLeapYear: function (year) {
        //if the day before the 1st March of the specified year is the 29th
        //and if so then it must be a leap year
        //used by februaryMaxDays:
        return new Date(year, 1, 29).getDate() == 29;
    },
    isDate: function (d) { //MM/DD/YYYY
        var dateString = "";
        if (d != null && d != 'undefined' && d != '') {
            if (Object.prototype.toString.call(d) === '[object Date]') {
                dateString = DateTimeUtilities.getMonth(d) + "/" + DateTimeUtilities.getDay(d) + "/" + DateTimeUtilities.getYear(d);
            } else {
                var arr = d.split("/");
                if (arr.length == 3) {
                    var arrMonth = arr[0].length == 1 ? "0" + arr[0] : arr[0];
                    var arrDay = arr[1].length == 1 ? "0" + arr[1] : arr[1];
                    var arrYear = arr[2];
                    dateString = arrMonth + "/" + arrDay + "/" + arrYear;
                }
            }
        }
        var blnReturn = false;
        d = '' + dateString;
        var expression = /^\d{2}\/\d{2}\/\d{4}$/;
        //check date, make sure that the date is in MM/DD/YYYY or M/D/YYYY format  
        if (expression.test(d)) {
            //change into date
            var ds = d.split("/");
            if (ds.length == 3) {
                //get the month and day out of the date
                var month = ds[0];
                var day = ds[1];
                //get the moths array
                var months = DateTimeUtilities.getMonthsList(d);
                //check the month and date against the array
                for (var i = 0; i < months.length; i++) {
                    if (String(months[i].Month) == month || months[i].Month2Digit == month) {
                        //month match, now check the day part
                        if (day <= months[i].Days) {
                            blnReturn = true;
                            break;
                        }
                    }
                }
            }
        }
        return blnReturn;
    },
    februaryMaxDays: function (d) {
        //used by getMonthsList:
        if (d == null || d == 'undefined') d = new Date;
        else d = new Date(d);
        var days = 28;
        if (DateTimeUtilities.isLeapYear(d.getFullYear()))
            days = 29;
        return days;
    }


}