【问题标题】:Get the device time format in Cordova在 Cordova 中获取设备时间格式
【发布时间】:2014-04-02 03:40:49
【问题描述】:

我在一个项目中使用 Cordova 2.9。

当应用程序以英语和普通话显示文本时,我使用 Moment.js 处理大量日期/时间格式。

我有一个功能请求,询问设备时间格式是 12 小时还是 24 小时格式,那么应用程序应该反映这一点。

目前我们始终使用 24 小时制。

有没有办法获取设备中设置的时间格式,然后使用它在应用程序级别设置时间格式?

【问题讨论】:

    标签: datetime cordova time phonegap-plugins


    【解决方案1】:

    你需要编写一个用于检测时间格式的插件。通过objective c在IOS中我们可以检测设备时间格式,与java(android)一样。所以检查下面的代码并编写一个插件。

    IOS

      NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
      [formatter setLocale:[NSLocale currentLocale]];
      [formatter setDateStyle:NSDateFormatterNoStyle];
      [formatter setTimeStyle:NSDateFormatterShortStyle];
      NSString *dateString = [formatter stringFromDate:[NSDate date]];
      NSRange amRange = [dateString rangeOfString:[formatter AMSymbol]];
      NSRange pmRange = [dateString rangeOfString:[formatter PMSymbol]];
      BOOL is24h = (amRange.location == NSNotFound && pmRange.location == NSNotFound);
    
      NSLog(@"IS 24 h format%@\n",(is24h ? @"YES" : @"NO"));
    

    安卓

    String value = android.provider.Settings.System.getString(context.getContentResolver(), android.provider.Settings.System.TIME_12_24);
    

    插件开发检查thisAndroidIOS

    【讨论】:

    • 谢谢。正如我所料,Cordova API 中没有任何内容。感谢领先。
    • @RyanP13 你为这个问题写过插件吗?
    • 对于那些感兴趣的人,我创建了一个仅适用于 iOS 的插件(暂时)github.com/greghuels/cordova-plugin-24hour-setting
    【解决方案2】:

    你可以只用cordova的内置globalization plugin.,例如运行的话,

    navigator.globalization.dateToString(
        new Date(),
        function (date) { alert('date: ' + date.value + '\n'); },
        function () { alert('Error getting dateString\n'); },
        { formatLength: 'short', selector: 'date and time' }
    );
    

    date.value 将保存一个显示时间格式的 dateString(只需检查字符串中是否包含“AM”或“PM”)。

    【讨论】:

    • 有没有办法把它做成时间戳格式?
    猜你喜欢
    • 1970-01-01
    • 2012-10-29
    • 1970-01-01
    • 1970-01-01
    • 2019-05-28
    • 2022-01-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多