angularionic-frameworktimemoment-timezoneangular-moment

Time format change according to time settings of phone in ionic5 angular9


I need to parse the time according to the phone settings(both android and IOS). If I select 24 hours in the device, need to show the 24 hour date in application and for the 12 hours selection, need to show the 12 hour time format in application. How can I find which time format is I selected in the device through the code.


Solution

  • You can use the following plugin: Globalization
    This is the Github repo for documentation: link

    And basically you will need to use getDatePattern methode provided by the plugin.

    navigator.globalization.getDatePattern(successCallback, errorCallback, options);
    

    This will returns a pattern string to format and parse dates according to the client's user preferences.
    For example:
    If set to the en_US locale, this example displays a popup dialog with text such as pattern: M/d/yyyy h:mm a :

    function checkDatePattern() {
        navigator.globalization.getDatePattern(
            function (date) { alert('pattern: ' + date.pattern + '\n'); },
            function () { alert('Error getting pattern\n'); },
            { formatLength: 'short', selector: 'date and time' }
        );
    }
    

    Then you can use the pattern to display your date and time accordingly.
    If you need to know more about date time patterns visit this link

    You can also take a look at Intl which gives you the ability to format your date and time without using a plugin:
    Intl.DateTimeFormat
    Intl.DateTimeFormat options