首页 > 解决方案 > 是否有获取设备使用哪种小时格式(12/24)的通用方法?

问题描述

我已经看到这个问题,OP 询问是否有办法检查设备用于 iOS 的小时格式。所选答案也有适用于 Android 的解决方案。但是,在我的 xamarin.forms 应用程序中,我无法在 iOS 中构建或运行该应用程序,因为我收到 Java.Interop 缺失错误。如果它使用 12 小时格式,我正在编写一个简单的方法来返回 bool。

public bool GetHourFormat()
{
    bool TwelveHourFormat = true;
    if (Device.RuntimePlatform == "iOS")
    {
        var dateFormatter = new NSDateFormatter();
        dateFormatter.DateStyle = NSDateFormatterStyle.None;
        dateFormatter.TimeStyle = NSDateFormatterStyle.Short;

        var dateString = dateFormatter.ToString(NSDate.Now);
        TwelveHourFormat =
        dateString.Contains(dateFormatter.AMSymbol) ||
        dateString.Contains(dateFormatter.PMSymbol);
    }
    else if (Device.RuntimePlatform == "Android")
    {
        TwelveHourFormat = Android.Text.Format.DateFormat.Is24HourFormat(Android.App.Application.Context);
    }
    return TwelveHourFormat;
}

有什么通用方法可以在不依赖平台的情况下获取这些信息?如果没有,我如何在两个平台上获取此信息?

标签: c#xamarin.forms

解决方案


我将使用Preprocessor,因此仅根据您使用的平台(Android / iOS)编译特定平台。

private bool CheckIsTwelveTimeFormat()
{
#if __ANDROID__
    // code in this #if block is only compiled on Android
    return !Android.Text.Format.DateFormat.Is24HourFormat(Android.App.Application.Context);
#elif __IOS__
    // code in this #elif block is only compiled on iOS
    var dateFormatter = new Foundation.NSDateFormatter {
        DateStyle = Foundation.NSDateFormatterStyle.None,
        TimeStyle = Foundation.NSDateFormatterStyle.Short
    };

    var dateString = dateFormatter.ToString(Foundation.NSDate.Now);
    var isTwelveHourFormat =
    dateString.Contains(dateFormatter.AMSymbol) ||
    dateString.Contains(dateFormatter.PMSymbol);
    return isTwelveHourFormat;
#endif
}

推荐阅读