1. const fs = require('fs');
  2. const path = require('path');
  3. /**
  4. * Formats time values based on a configuration file.
  5. * @param {string} timeValue The time value to format (e.g., '2024-02-29T10:30:45Z').
  6. * @param {object} config The configuration object.
  7. * @returns {string} The formatted time value, or the original value if formatting fails.
  8. */
  9. function formatTime(timeValue, config) {
  10. try {
  11. const format = config.format || 'YYYY-MM-DD HH:mm:ss'; // Default format
  12. const date = new Date(timeValue);
  13. if (isNaN(date.getTime())) {
  14. console.warn(`Invalid date/time format: ${timeValue}. Returning original value.`);
  15. return timeValue;
  16. }
  17. return date.toLocaleString(config.locale || 'en-US', { // Default locale
  18. timeZone: config.timezone || 'UTC',
  19. year: format.includes('YYYY') ? 'numeric' : '2-digit',
  20. month: format.includes('MM') ? '2-digit' : 'long',
  21. day: format.includes('DD') ? '2-digit' : 'numeric',
  22. hour: format.includes('HH') ? '2-digit' : 'numeric',
  23. minute: format.includes('mm') ? '2-digit' : 'numeric',
  24. second: format.includes('ss') ? '2-digit' : 'numeric',
  25. });
  26. } catch (error) {
  27. console.error(`Error formatting time: ${error}. Returning original value.`);
  28. return timeValue;
  29. }
  30. }
  31. /**
  32. * Loads the configuration file.
  33. * @param {string} configFilePath The path to the configuration file.
  34. * @returns {object} The configuration object.
  35. */
  36. function loadConfig(configFilePath) {
  37. try {
  38. const configContent = fs.readFileSync(configFilePath, 'utf8');
  39. const config = JSON.parse(configContent);
  40. return config;
  41. } catch (error) {
  42. console.error(`Error loading config file: ${error}. Using default configuration.`);
  43. return {
  44. format: 'YYYY-MM-DD HH:mm:ss',
  45. locale: 'en-US',
  46. timezone: 'UTC'
  47. };
  48. }
  49. }
  50. /**
  51. * Main function to process the time value.
  52. * @param {string} timeValue The time value to format.
  53. * @param {string} configFilePath The path to the configuration file.
  54. * @returns {string} The formatted time value.
  55. */
  56. function processTime(timeValue, configFilePath) {
  57. const config = loadConfig(configFilePath);
  58. return formatTime(timeValue, config);
  59. }
  60. module.exports = { processTime };

Add your comment