Skip to content

Instantly share code, notes, and snippets.

@vwochnik vwochnik/index.js
Last active Oct 29, 2016

Embed
What would you like to do?
Randomize ghost post dates for sqlite3 database
var sqlite3 = require('sqlite3').verbose();
var file = process.argv.slice(-1).pop();
var db = new sqlite3.Database(file);
var start = new Date("2016-01-01"),
end = new Date("2016-10-20");
db.serialize(function() {
var stmt = db.prepare("UPDATE posts SET created_at = ?, updated_at = ?, published_at = ? WHERE id = ?")
db.each("SELECT id, created_at, updated_at, published_at FROM posts", function(err, row) {
if (err) throw new Error(err);
var date = randomDate(start, end, 3, 21),
sdate = formatDate(date);
stmt.run(sdate, sdate, sdate, row.id);
}, function() {
stmt.finalize();
});
});
db.close();
function formatDate(date) {
return date.toISOString().replace('T', ' ').replace(/\..*$/, '')
}
// adopted from http://stackoverflow.com/questions/31378526/generate-random-date-between-two-dates-and-times-in-javascript
function randomDate(start, end, startHour, endHour) {
var date = new Date(+start + Math.random() * (end - start));
var hour = startHour + Math.random() * (endHour - startHour) | 0;
date.setHours(hour);
return date;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.