Skip to content

Instantly share code, notes, and snippets.

@zachdunn
Created April 15, 2016 15:29
Show Gist options
  • Save zachdunn/0dea49ecfc8526c0174cf846509b8c8c to your computer and use it in GitHub Desktop.
Save zachdunn/0dea49ecfc8526c0174cf846509b8c8c to your computer and use it in GitHub Desktop.
Utils for working with timestamps
import moment from 'moment';
import _ from 'lodash';
/**
* Transform given timestamp properties into moment objects
* Example usage:
* myEvent = transformTimestamps(myEvent, ['started_at', 'confirmation.confirmed_at'])
* @param {Object} targetObject Object to transform properties for
* @param {Array} targetKeys Array of paths to timestamp property
* @return {Object} Transformed targetObject
*/
export function transformTimestamps (targetObject, targetKeys) {
targetKeys.forEach( (targetKey) => {
let originalTimestamp = _.get(targetObject, targetKey);
// Make sure the value actually exists and it's a valid timestamp
if (originalTimestamp && moment(originalTimestamp).isValid()) {
// Convert to a moment object
_.set(targetObject, targetKey, moment(originalTimestamp));
}
});
return targetObject;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment