const fs = require('fs');
const path = require('path');
/**
* Formats time values based on a configuration file.
* @param {string} timeValue The time value to format (e.g., '2024-02-29T10:30:45Z').
* @param {object} config The configuration object.
* @returns {string} The formatted time value, or the original value if formatting fails.
*/
function formatTime(timeValue, config) {
try {
const format = config.format || 'YYYY-MM-DD HH:mm:ss'; // Default format
const date = new Date(timeValue);
if (isNaN(date.getTime())) {
console.warn(`Invalid date/time format: ${timeValue}. Returning original value.`);
return timeValue;
}
return date.toLocaleString(config.locale || 'en-US', { // Default locale
timeZone: config.timezone || 'UTC',
year: format.includes('YYYY') ? 'numeric' : '2-digit',
month: format.includes('MM') ? '2-digit' : 'long',
day: format.includes('DD') ? '2-digit' : 'numeric',
hour: format.includes('HH') ? '2-digit' : 'numeric',
minute: format.includes('mm') ? '2-digit' : 'numeric',
second: format.includes('ss') ? '2-digit' : 'numeric',
});
} catch (error) {
console.error(`Error formatting time: ${error}. Returning original value.`);
return timeValue;
}
}
/**
* Loads the configuration file.
* @param {string} configFilePath The path to the configuration file.
* @returns {object} The configuration object.
*/
function loadConfig(configFilePath) {
try {
const configContent = fs.readFileSync(configFilePath, 'utf8');
const config = JSON.parse(configContent);
return config;
} catch (error) {
console.error(`Error loading config file: ${error}. Using default configuration.`);
return {
format: 'YYYY-MM-DD HH:mm:ss',
locale: 'en-US',
timezone: 'UTC'
};
}
}
/**
* Main function to process the time value.
* @param {string} timeValue The time value to format.
* @param {string} configFilePath The path to the configuration file.
* @returns {string} The formatted time value.
*/
function processTime(timeValue, configFilePath) {
const config = loadConfig(configFilePath);
return formatTime(timeValue, config);
}
module.exports = { processTime };
Add your comment