Check if the device clock is using the 24 Hour format


#1

I’m trying to create a multi-platform method for checking if the device clock is set to 24 hour time. Here is how I current

export function is24HourFormat(): boolean {
  try {
    if (platform.isAndroid) {
      let context = app.android.context;
      return android.text.format.DateFormat.is24HourFormat(context);
    } else {
      let nsDateFormatter = global.NSDateFormatter.alloc().init()
      let formatedHoursString = nsDateFormatter.dateFormatFromTemplate("j", 0, NSLocale.currentLocale);
      let containsA = formatedHoursString.rangeOfString("a");
      let is24Hour = containsA.location !== global.NSNotFound;

      return is24Hour;
    }
  } catch (e) {
    console.error(">>> Error getting clock setting: " + e.message);
  }
}

I’m getting error on iOS right now which states that nsDateFormatter.dateFormatFromTemplate is not a function. How could I write the Objective-C code I have codeHere in such a way so that it works in Nativescript?


#2

If you write it like this, that formatedHours variable is a plain old JS string, so you can use .indexOf:

let formatedHours: string = NSDateFormatter.dateFormatFromTemplateOptionsLocale("j", 0, NSLocale.currentLocale);

#4

That worked like a charm, thanks!