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

990 views Asked by At

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.

2

There are 2 answers

0
Elmehdi On BEST ANSWER

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

0
Carles Mateo On

You are talking about Locale. I think you're looking to use ion-datetime. It resolves all you need and by default it will use the Locale configuration of the user on the phone.

Important: ion-datetime will by default display values relative to the user's timezone. Given a value of 09:00:00+01:00, the datetime component will display it as 04:00:00-04:00 for users in a -04:00 timezone offset. To change the display to use a different timezone, use the displayTimezone property described below.

All the info you need with many samples is in here: https://ionicframework.com/docs/api/datetime

Cheers.