skip to Main Content

How do I obtain the preferred hourCycle of the user’s current locale? I’ve tried a few locales ((new Intl.Locale('en-US')).hourCycle) in both Firefox 131 and Chrome 129, but both return undefined.

console.log(new Intl.Locale('en-US').hourCycle);

2

Answers


  1. you can manually determine the hourCycle by formatting a date and checking the output:

    function getHourCycle() {
        const date = new Date(2023, 0, 1, 15); // 3 PM
        const formatter12 = new Intl.DateTimeFormat(navigator.language, { hour: 'numeric', hour12: true });
        //const formatter24 = new Intl.DateTimeFormat(navigator.language, { hour: 'numeric', hour12: false });
    
        const formatted12 = formatter12.format(date);
        //const formatted24 = formatter24.format(date);
    
        // Check if the output indicates a 12-hour format
        if (formatted12.includes('PM') || formatted12.includes('AM')) {
            return 'h12';
        } else {
            return 'h24';
        }
    }
    
    const hourCycle = getHourCycle();
    console.log(hourCycle);
    

    The output from the 12-hour formatter includes "AM" or "PM," otherwise, it defaults to 24-hour.

    Login or Signup to reply.
  2. Intl.Locale() only returns this information if it’s passed via the locale tag or the hourCycle option. To get the hourCycle even if neither of these apply, you need to use Intl.DateTimeFormat().resolvedOptions() instead (note that you need to specify the timeStyle option):

    const dateTimeFormat = new Intl.DateTimeFormat('en-US', { timeStyle: 'long' });
    const { hourCycle } = dateTimeFormat.resolvedOptions();
    console.log(hourCycle);
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search