Skip to content

Instantly share code, notes, and snippets.

@wilmoore
Last active December 29, 2024 02:38
Show Gist options
  • Select an option

  • Save wilmoore/e6b562216b7926dfcdb63d3210f0c4b9 to your computer and use it in GitHub Desktop.

Select an option

Save wilmoore/e6b562216b7926dfcdb63d3210f0c4b9 to your computer and use it in GitHub Desktop.
Business :: Ideas :: GistWiz :: Development :: Scheduler

Business :: Ideas :: GistWiz :: Development :: Scheduler

⪼ Made with 💜 by Polyglot.

assistant

Scheduler

Get Date

new Date().toLocaleString()
'28/12/2024, 12:05:30 pm'
(?P<DD>[\d]{2})\/(?P<MM>[\d]{2})\/(?P<YYYY>[\d]{4}), (?P<hh>[\d]{2}):(?P<mm>[\d]{2}):(?P<ss>[\d]{2}) (?P<AMPM>(AM|PM))

CleanShot 2024-12-28 at 12 06 40@2x

const ms = require("ms");

function getLocaleDateComponents(delta = "0") {
  const regex = /(?<DD>[\d]{2})\/(?<MM>[\d]{2})\/(?<YYYY>[\d]{4}), (?<hh>[\d]{2}):(?<mm>[\d]{2}):(?<ss>[\d]{2}) (?<AMPM>AM|PM)/;

  // Get the current date
  const now = new Date();

  // Convert the delta to milliseconds and add it to the current date
  const deltaMs = ms(delta);
  if (isNaN(deltaMs)) {
    throw new Error(`Invalid delta format: "${delta}".`);
  }
  const adjustedDate = new Date(now.getTime() + deltaMs);

  // Format the adjusted date using a specific locale
  const options = {
    day: "2-digit",
    month: "2-digit",
    year: "numeric",
    hour: "2-digit",
    minute: "2-digit",
    second: "2-digit",
    hour12: true, // Ensures AM/PM format
  };
  const formattedDate = adjustedDate.toLocaleString("en-US", options);

  // Parse the formatted date using regex
  const match = formattedDate.match(regex);
  if (!match) {
    console.error("Formatted Date:", formattedDate);
    throw new Error("Failed to parse the date string.");
  }

  // Return the capture groups
  return match.groups;
}

// Example usage
try {
  const components = getLocaleDateComponents("10m");
  console.log(components);
} catch (error) {
  console.error(error.message);
}

Main

> getLocaleDateComponents()
[Object: null prototype] {
  DD: '12',
  MM: '28',
  YYYY: '2024',
  hh: '12',
  mm: '13',
  ss: '10',
  AMPM: 'PM'
}
> let { YYYY, MM, DD, hh, mm, ss } = getLocaleDateComponents()
undefined
> console.log(`${YYYY}${MM}${DD}${hh}${mm}.${ss}`)
202428121214.23

> getLocaleDateComponents()
[Object: null prototype] {
  DD: '12',
  MM: '28',
  YYYY: '2024',
  hh: '12',
  mm: '30',
  ss: '22',
  AMPM: 'PM'
}
> getLocaleDateComponents("10m")
[Object: null prototype] {
  DD: '12',
  MM: '28',
  YYYY: '2024',
  hh: '12',
  mm: '40',
  ss: '26',
  AMPM: 'PM'
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment