Last active
January 25, 2018 07:58
-
-
Save garbados/6325276 to your computer and use it in GitHub Desktop.
Sample CouchDB map functions for working with dates without a library.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function(doc){ | |
// handle a custom format using methods in the date object | |
var format = "{getFullYear}/{getMonth}/{getDate}", | |
date = new Date(doc.created_at), | |
// use a regular expression to replace parts of our format string | |
formatted_date = format.replace(/\{(\w+)\}/g, function(str, func){ | |
var time = date[func](); | |
// if `func` is `getMonth` we must offset by one | |
if(func === 'getMonth'){ | |
time += 1; | |
} | |
return time; | |
}); | |
emit(formatted_date, doc.created_at); | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function(doc){ | |
// use built-in methods for ISO formatting | |
var date = new Date(doc.created_at); | |
emit(date.getTime(), date.toISOString()); | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function(doc){ | |
// given a format string as a regex... | |
var format = /^(\d{1,4})\/(\d{1,2})\/(\d{1,2})$/; | |
if(doc.key){ | |
// we check if they match | |
var match = doc.key.match(format); | |
if(match){ | |
// and use our knowledge of what each capture field should be | |
// to create a date object | |
var date = new Date(match[1], match[2], match[3]); | |
emit(doc.key, date.getTime()); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment