Skip to content

Commit

Permalink
Added support for automatic detection of Date objects.
Browse files Browse the repository at this point in the history
  • Loading branch information
jeff-tenhave committed Nov 6, 2017
1 parent 3b5ef30 commit f675ae1
Show file tree
Hide file tree
Showing 4 changed files with 10 additions and 4 deletions.
2 changes: 1 addition & 1 deletion json2dbf.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ var dbf = require('./'),
fs = require('fs');

var buf = dbf.structure([
{foo:'bar',noo:10},
{foo:'bar',noo:new Date()},
{foo:'louie'}
]);

Expand Down
3 changes: 2 additions & 1 deletion src/fields.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ var types = {
string: 'C',
number: 'N',
boolean: 'L',
date: 'D',
// type to use if all values of a field are null
null: 'C'
};
Expand Down Expand Up @@ -36,7 +37,7 @@ function inherit(a, b) {

function obj(_) {
var fields = {}, o = [];
for (var p in _) fields[p] = _[p] === null ? 'null' : typeof _[p];
for (var p in _) fields[p] = _[p] === null ? 'null' : _[p] instanceof Date ? 'date' : typeof _[p];
for (var n in fields) {
var t = types[fields[n]];
if(t){
Expand Down
5 changes: 5 additions & 0 deletions src/lib.js
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,11 @@ module.exports.writeField = function writeField(view, fieldLength, str, offset)
return offset;
};

module.exports.writeDate = function(date) {
if(!date || isNaN(date.getTime())) return " ";
return ("0000"+date.getFullYear()).slice(-4) + ("00"+(date.getMonth()+1)).slice(-2) + ("00"+date.getDate()).slice(-2);
};

/**
* @param {string} str
* @returns {object}
Expand Down
4 changes: 2 additions & 2 deletions src/structure.js
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ module.exports = function structure(data, meta) {
view.setUint8(0, 0x03);
// date of last update
view.setUint8(1, now.getFullYear() - 1900);
view.setUint8(2, now.getMonth());
view.setUint8(2, now.getMonth()+1);
view.setUint8(3, now.getDate());
// number of records
view.setUint32(4, data.length, true);
Expand Down Expand Up @@ -77,7 +77,7 @@ module.exports = function structure(data, meta) {
// date
case 'D':
offset = lib.writeField(view, 8,
lib.lpad(val.toString(), 8, ' '), offset);
lib.writeDate(val), offset);
break;

// number
Expand Down

0 comments on commit f675ae1

Please sign in to comment.