Archive

Posts Tagged ‘JavaScript’

Religion in American History: Exhibiting Faith, part II: Toward a Public [digital] Religious Studies

 

Religion in American History: Exhibiting Faith, part II: Toward a Public [digital] Religious Studies.

Advertisements

An API for the Web: Learning YQL – Tuts+ Code Tutorial

Beginners Guide to DOM Selection with jQuery

Categories: .Of Interest Tags: ,

Determining if an object property exists [JAVASCRIPT] | NCZOnline

Categories: .Of Interest Tags: ,

The Problem with Testing for NaN in JavaScript · Design Pepper

Chrome DevTools — Google Developers

Chrome DevTools — Google Developers.

Styling console output with CSS

 

Enhanced by Zemanta

Google Docs spreadsheet script: compare dates, highlight past dates, highlight weekends, and highlight today

October 30, 2013 Leave a comment
screenshot of Google spreadsheet with 3 custom highlighting functions applied

A Google spreadsheet with my 3 custom highlighting functions applied

ORIGINAL PROBLEM

I spent hours tonight struggling with this Google Apps script I wrote to serve as custom functions or advanced macros. I adapted it from this StackOverflow post. The main issue I ran into was comparing dates. Here is my research path, and hopefully, some indicator as to why it took so long:

STEPS and MISSTEPS TAKEN TO SOLVE

  • Looked for built-in function in Google spreadsheet to do conditional formatting on weekends. No weekend selector and no built-in way to conditionally format the whole row based on the contents of one cell. (time: 35 min)
  • Discovered the only way to do this was to write a Google Apps script. I’ve never heard of Google Script until today. Now I had to look up basic Google Script tutorials. (time: 1 hr 30 min)
  • Wrote and tested code to highlight weekends. Date functions worked fine. (time: 1 hr)
  • Wrote code to highlight dates older than today. Worked, but highlighted today’s date also, which is incorrect. Investigated this issue for almost 2 hours. (time: 1 hr 38 min)
  • Discovered that Google Apps script is based heavily on JavaScript. Was then able to research from a JavaScript perspective. Ok, I should be almost there right?-Wrong! The major stumbling block I ran into has to do with how JavaScript handles date comparisons. There were two main problems:
    1. The new Date() object was not comparing correctly to today’s date. The issue, I found, is well-known to many JavaScript developers: comparing two Date() objects includes the time component, down to the millisecond, so they are never going to be equivalent. (it’s issues like these that make working with libraries like jQuery and Backbone more desirable than raw JavaScript coding.)The solution to this problem was to remove the time component with toDateString(). (time: 30 min)
    2. But that still didn’t make the comparisons work. The issue had something to do with comparing two objects. The solution was given on StackOverflow as essentially converting date objects to strings before comparing. I found the way to do that was with the dot operator and the non-intuitive getTime() function. (time: 15 min)
  • There was still one more snag though. Apparently you can’t assign the getTime() component in a variable like this:
    var today_noTime = new Date(today.toDateString().getTime());
    

    because it just fails. I’m not sure of the technical reasons for this, but it is very annoying in practice.The ultimate solution was to use getTime() as a dot-method on your Date() objects in the direct comparison statement, like this:

    if (today_noTime.getTime() == date_noTime.getTime()) {
        Logger.log("****** Dates are EQUAL ******");
    }

    (time: 15 min)

CONCLUSION

It took around 5 hrs to finally find all the answers. Along the way, I struggled a bunch, learned a lot and am grateful for the experience. However, my one real frustration was that there was no one clear website saying “known issues with comparing time and date in JavaScript”–there was just no such thing. I hope that this post has explained some of these issues precisely enough that it will save you some time.

FINAL SCRIPT

Here is the final complete script:

/*
 * Creator: Eric Hepperle
 * Date:    10/29/13
 * Purpose: Google Script for Spreadsheet.
 *           - Shades rows with weekend dates in (column 2) light gray.
 *           - Shades rows for past days with dark gray.
 *           - Highlights today with yellow background.
 *
 * Notes:   Adapted from code found here:
 *           http://stackoverflow.com/questions/15730638/
 *           google-doc-spreedsheet-conditional-formatting-script
 *
 * Colors:
 *           #B8B8B8 = med gray; past dates.
 *           #E8E8E8 = light gray; weekends.
 */
function colorAll() {
    var sheet = SpreadsheetApp.getActiveSheet();
    var startRow = 6;
    var endRow = sheet.getLastRow();

    for (var r = startRow; r <= endRow; r++) {
        colorRow(r);
    }
}

function colorRow(r) {
    var sheet = SpreadsheetApp.getActiveSheet();
    var dataRange = sheet.getRange(r, 1, 1, 5);

    var data = dataRange.getValues();
    var row = data[0];

    // eric's vars
    var date = row[1]; // 2nd column
    var dayOfWeek = date.getDay();

    Logger.log("*** Logging dayOfWeek " + r + " now ***");
    Logger.log(dayOfWeek);

    // if dayOfWeek is Sat or Sun:
    if (dayOfWeek == 0 || dayOfWeek == 6) {
        if (row[0] === "") {
            dataRange.setBackgroundRGB(255, 255, 255);
        } else {
            dataRange.setBackground("#E8E8E8");
        }
    }

    var today = new Date();
    Logger.log("*** today ***");
    Logger.log(today);
    Logger.log("*** date ***");
    Logger.log(date);

    // remove time component from date for comparison
    today_noTime = new Date(today.toDateString());
    date_noTime = new Date(date.toDateString());

    /*
	Logger.log("today_noTime:");
	Logger.log(today_noTime);

	Logger.log("date_noTime:");
	Logger.log(date_noTime);

	if(today_noTime.getTime() == date_noTime.getTime()){
		Logger.log("****** Dates are EQUAL ******");
	}
    */

    // if date is older than today, mark it as such
    if (date_noTime.getTime() < today_noTime.getTime()) {
        dataRange.setBackground("#B8B8B8");
    }

    if (date_noTime.getTime() == today_noTime.getTime()) {
        dataRange.setBackground("yellow");
    }

    SpreadsheetApp.flush();
}

function onEdit(event) {
    var r = event.source.getActiveRange().getRowIndex();
    if (r >= 2) {
        colorRow(r);
    }
}