UNPKG

field-time-new

Version:

A Blockly date picker field that uses the browser's date picker.

35 lines (31 loc) 1.54 kB
/** * Get the string formatted locally to the user. * * @param dateString A string in the format 'yyyy-mm-dd' * @returns the locale date string for the date. */ export function getLocaleTimeString(dateString: string): string { // NOTE: `date.toLocaleDateString()` will be the day before for western dates // due to an unspecified time & timezone assuming midnight at GMT+0. const date = parseTimeString(dateString); // NOTE: This format varies per region. // Ex: "5/12/2023", "12/05/2023", "12.5.2023", "2023/5/12", "१२/५/२०२३" // const language = navigator.language ?? 'en-US'; // See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/DateTimeFormat#using_options return new Intl.DateTimeFormat(undefined, { // Print the date for GMT+0 since the date object assumes midnight at GMT+0. hour: '2-digit', minute: '2-digit', second: '2-digit', hour12: false, // Use 12-hour clock // timeZone: 'UTC', }).format(date); } function parseTimeString(timeString: string): Date { // const [time, period] = timeString.split(' '); const [hours, minutes, seconds] = timeString.split(':').map(Number); // Convert hours to 24-hour format if necessary // const adjustedHours = period === 'PM' && hours < 12 ? hours + 12 : (period === 'AM' && hours === 12 ? 0 : hours); // Create a date object with a fixed date and the parsed time return new Date(2024, 7, 9, hours, minutes, seconds); // Month is 0-indexed }