Skip to content

Instantly share code, notes, and snippets.

@paazmaya
Created November 10, 2015 16:58
Show Gist options
  • Save paazmaya/76d6a4a1fc6267650739 to your computer and use it in GitHub Desktop.
Save paazmaya/76d6a4a1fc6267650739 to your computer and use it in GitHub Desktop.
Fix unix dates to suitable in frontmatter
/**
* Convert unix timestamps to ISO times in frontmatter
*/
'use strict';
const fs = require('fs'),
path = require('path'),
yfm = require('yaml-front-matter');
// 1277284080 --> 2014-03-22T17:44:00+0200
// 1. Find Markdown files
// 2. read their frontmatter
// 3. fix date
// 4. string replace in original contents
var directory = 'stories/published/';
var list = fs.readdirSync(directory);
list.forEach(function eachFile(filename) {
var filepath = path.join(directory, filename);
console.log('Reading ' + filepath);
var raw = fs.readFileSync(filepath, 'utf8');
var data = yfm.loadFront(raw);
if (data.hasOwnProperty('image') && data.image.hasOwnProperty('modified')) {
var orig = String(data.image.modified);
if (orig.substr(0, 2) !== '20') {
var date = new Date(data['image']['modified'] * 1000);
var suitable = toSuitableString(date);
raw = raw.replace(orig, suitable);
}
fs.writeFileSync(filepath, raw, 'utf8');
}
/*
publishtime: 1277284080
modified: 1277285361
*/
});
function pad(number) {
if (number < 10) {
return '0' + number;
}
return number;
}
function toSuitableString(date) {
return '\'' + date.getFullYear() +
'-' + pad(date.getMonth() + 1) +
'-' + pad(date.getDate()) +
'T' + pad(date.getHours()) +
':' + pad(date.getMinutes()) +
':' + pad(date.getSeconds()) +
'+' + pad(Math.abs(date.getTimezoneOffset() / 60 * 100)) + '\'';
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment