c# - 是否有获取设备使用哪种小时格式(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;
}
有什么通用方法可以在不依赖平台的情况下获取这些信息?如果没有,我如何在两个平台上获取此信息?
解决方案
我将使用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
}
推荐阅读
- arrays - 在 Dymola 中编译大数组
- android - 回收站视图的项目背景不会在点击事件上更新?
- reporting-services - 报表服务 rdl Visual Studio 2008
- javascript - Vue.js Vuetify.js - 未知的自定义元素:
, 您是否正确注册了组件? - python - 使用 Flask SQLAlchemy 选择 DISTINCT YEAR()
- java - Application vs ApplicationTest:不同的事件调度?
- angular - 如何限制对文本框的输入,使其仅接受数字和小数点(至少 4 位小数,例如 192.168.192.192)?
- rest - 美化或缩短 REST API 的 URL
- zapier - 无法取消暂停以 zapier 中的搜索结尾的 Zap?
- google-apps-script - 可以为 Google 应用脚本中的脚本代码设置密码吗?