Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

IndexedDB and Date Example

DZone's Guide to

IndexedDB and Date Example

· Web Dev Zone
Free Resource

Make the transition to Node.js if you are a Java, PHP, Rails or .NET developer with these resources to help jumpstart your Node.js knowledge plus pick up some development tips.  Brought to you in partnership with IBM.

About an hour ago I gave a presentation on IndexedDB. One of the attendees asked about dates and being able to filter based on a date range. I told him that my assumption was that you would need to convert the dates into numbers and use a number-based range. Turns out I was wrong. Here is an example.

I began by creating an objectstore that used an index on the created field. Since our intent is to search via a date field, I decided "created" would be a good name. I also named my objectstore as "data". Boring, but it works.

var openRequest = indexedDB.open("idbpreso_date1",1);

openRequest.onupgradeneeded = function(e) {
	var thisDB = e.target.result;

	if(!thisDB.objectStoreNames.contains("data")) {
		var os = thisDB.createObjectStore("data", {autoIncrement:true});
		os.createIndex("created", "created", {unique:false});
	}
}

Next - I built a simple way to seed data. I based on a button click event to add 10 objects. Each object will have one property, created, and the date object will be based on a random date from now till 7 days in the future.

function doSeed() {
    var now = new Date();
    
    for(var i=0; i<10; i++) {
        var dayDiff = getRandomInt(1, 7);
        var thisDate = new Date();
        thisDate.setDate(now.getDate() + dayDiff);
        db.transaction(["data"],"readwrite").objectStore("data").add({created:thisDate});
    }
}
 
//Credit: Mozilla Developer Center
function getRandomInt (min, max) {
    return Math.floor(Math.random() * (max - min + 1)) + min;
}    

Note that since IndexedDB calls are asynchronous, my code should handle updating the user to let them know when the operation is done. Since this is just a quick demo though, and since that add operation will complete incredibly fast, I decided to not worry about it.

So at this point we'd have an application that lets us add data containing a created property with a valid JavaScript date. Note I didn't change it to milliseconds. I just passed it in as is.

For the final portion I added two date fields on my page. In Chrome this is rendered nicely:

Based on these, I can then create an IndexedDB range of either bounds, lowerBounds, or upperBounds. I.e., give me crap either after a date, before a date, or inside a date range.

function doSearch() {
    var fromDate = document.querySelector("#fromDate").value;
    var toDate = document.querySelector("#toDate").value;

  var range;

	if(fromDate == "" && toDate == "") return;

    var transaction = db.transaction(["data"],"readonly");
	var store = transaction.objectStore("data");
	var index = store.index("created");

    if(fromDate != "") fromDate = new Date(fromDate);
    if(toDate != "") toDate = new Date(toDate);
    
    if(fromDate != "" && toDate != "") {
		range = IDBKeyRange.bound(fromDate, toDate);
	} else if(fromDate == "") {
		range = IDBKeyRange.upperBound(toDate);
	} else {
		range = IDBKeyRange.lowerBound(fromDate);
	}

	var s = "";
	index.openCursor(range).onsuccess = function(e) {
		var cursor = e.target.result;
		if(cursor) {
			s += "<h2>Key "+cursor.key+"</h2><p>";
			for(var field in cursor.value) {
				s+= field+"="+cursor.value[field]+"<br/>";
			}
			s+="</p>";
			cursor.continue();
		}
		document.querySelector("#status").innerHTML = s;
	}

}

The only conversion required here was to take the user input and turn it into "real" date objects. Once done, everything works great:

You can run the full demo below.

Learn why developers are gravitating towards Node and its ability to retain and leverage the skills of JavaScript developers and the ability to deliver projects faster than other languages can.  Brought to you in partnership with IBM.

Topics:

Published at DZone with permission of Raymond Camden, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

The best of DZone straight to your inbox.

SEE AN EXAMPLE
Please provide a valid email address.

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.
Subscribe

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}