From b9cd6845696ef85bb72cacb8ebf33ada8ee0bcca Mon Sep 17 00:00:00 2001 From: Chesterkxng Date: Sun, 12 Apr 2026 14:45:33 +0200 Subject: [PATCH] chore: service refactored - accept only ms timestamps - combined logic - date util parser usage --- .../time/convert-unix-to-date/service.ts | 146 ++++++------------ 1 file changed, 50 insertions(+), 96 deletions(-) diff --git a/src/pages/tools/time/convert-unix-to-date/service.ts b/src/pages/tools/time/convert-unix-to-date/service.ts index 5ff2f18..8e5781b 100644 --- a/src/pages/tools/time/convert-unix-to-date/service.ts +++ b/src/pages/tools/time/convert-unix-to-date/service.ts @@ -1,25 +1,19 @@ import { containsOnlyDigits } from '@utils/string'; - -export function convertString( - input: string, - mode: string, - useLocalTime: boolean, - withLabel: boolean -): string { - if (mode === 'unix-to-date') { - return convertUnixToDate(input, withLabel, useLocalTime); - } else { - return convertDateToUnix(input, useLocalTime); - } -} +import InitialValuesType from './types'; +import { parseDateInput } from '@utils/time'; // Unix to Date function computeUnixToDate(input: string, useLocalTime: boolean): string { if (!containsOnlyDigits(input)) { return ''; } + + if (input.length > 10) return 'ms not supported, divide by 1000'; + const timestamp = parseInt(input, 10); + const date = new Date(timestamp * 1000); // Convert from seconds to milliseconds + if (isNaN(date.getTime())) return ''; if (useLocalTime) { const year = date.getFullYear(); @@ -34,102 +28,62 @@ function computeUnixToDate(input: string, useLocalTime: boolean): string { } } -export function convertUnixToDate( - input: string, - withLabel: boolean, - useLocalTime: boolean -): string { - const result: string[] = []; - - const lines = input.split('\n'); - - lines.forEach((line) => { - const parts = line.split(' '); - const timestamp = parts[0]; - const formattedDate = computeUnixToDate(timestamp, useLocalTime); - - const label = !useLocalTime && withLabel ? ' UTC' : ''; - result.push(formattedDate ? `${formattedDate}${label}` : ''); - }); - - return result.join('\n'); -} - // Date to Unix function computeDateToUnix(input: string, useLocalTime: boolean): string { try { - // Extract Data - const splitInput = input.split(' '); - const timeFrame = splitInput[0] + ' ' + splitInput[1]; - const utcOffset = splitInput.length > 2 ? splitInput[2] : null; + const { dateTime, utcOffset } = parseDateInput(input); + const normalized = dateTime.includes(':') + ? dateTime + : `${dateTime}T00:00:00`; - // Convert into Unix (This Has The Local Offset) - const localUnixValue: number = Date.parse(timeFrame) / 1000; - - // Unsuccesful Conversion - if (isNaN(localUnixValue)) { - return ''; - } - - // Case 1: Base Scenario (Assume Time with GMT +00) - if (!useLocalTime && !utcOffset) { - const processedDateTime = convertToGMTZero(localUnixValue); - return `${processedDateTime}`; - } - - // Case 2: Time Given with Custom Offset - if (!useLocalTime && utcOffset) { - // Verify Offset (-12:00 to +14.00 in 15 Minute Intervals) - const regexMatch = utcOffset.match(/^[+-](0\d|1[0-4]):(00|15|30|45)$/); - - // Invalid Regex - if (!regexMatch) { - return ''; - } - - // Variables to Be Processed - const hours = Number(regexMatch[1]); - const minutes = Number(regexMatch[2]) + hours * 60; - const offset = minutes * 60; - - // Remove The Offset to The Time (Opposite of First Symbol - If Input Time is +08:00 Then We Need to Deduct by 8 Hours) - const processedDateTime = convertToGMTZero(localUnixValue) - offset; - return `${processedDateTime}`; - } - - // Case 3: Local (Time Given is Local Time) if (useLocalTime) { - return `${localUnixValue}`; + const localOffsetMinutes = new Date().getTimezoneOffset(); + const sign = localOffsetMinutes <= 0 ? '+' : '-'; + const absMinutes = Math.abs(localOffsetMinutes); + const hh = String(Math.floor(absMinutes / 60)).padStart(2, '0'); + const mm = String(absMinutes % 60).padStart(2, '0'); + const unix = Date.parse(`${normalized}${sign}${hh}:${mm}`) / 1000; + return isNaN(unix) ? '' : `${unix}`; } - } catch (err) { - // Not Using Local Time (Either UTC is Given or Assume +00) + + if (utcOffset) { + const valid = utcOffset.match(/^[+-](0\d|1[0-4]):(00|15|30|45)$|^Z$/); + if (!valid) return ''; + const unix = + Date.parse(`${normalized}${utcOffset === 'Z' ? 'Z' : utcOffset}`) / + 1000; + return isNaN(unix) ? '' : `${unix}`; + } + + // Default: treat as UTC + const unix = Date.parse(`${normalized}Z`) / 1000; + return isNaN(unix) ? '' : `${unix}`; + } catch { return ''; } - return ''; } -function convertToGMTZero(localUnixValue: number): number { - // Get A Reference Object - const refTimeDate = new Date(); - const offsetMinutes = refTimeDate.getTimezoneOffset(); - - // Remove the Offset - const processedDateTime = localUnixValue - offsetMinutes * 60; - return processedDateTime; -} - -function convertDateToUnix(input: string, useLocalTime: boolean): string { - // Empty Input +export function UnixDateConverter( + input: string, + options: InitialValuesType +): string { if (!input) return ''; - const result: string[] = []; + const { mode, useLocalTime, withLabel } = options; + const lines = input.split('\n'); - // Process Input Lines - lines.forEach((line) => { - const formattedDate = computeDateToUnix(line, useLocalTime); - result.push(formattedDate); - }); + if (mode === 'unix-to-date') { + const label = !useLocalTime && withLabel ? ' UTC' : ''; + return lines + .map((line) => { + const formattedDate = computeUnixToDate(line.trim(), useLocalTime); + return formattedDate ? `${formattedDate}${label}` : ''; + }) + .join('\n'); + } - return result.join('\n'); + return lines + .map((line) => computeDateToUnix(line.trim(), useLocalTime)) + .join('\n'); }