【问题标题】:How to check if a String is a valid Joda DateTime如何检查字符串是否是有效的 Joda DateTime
【发布时间】:2014-01-10 12:49:46
【问题描述】:

我的数据库中存储了以下字符串

cursor.getString(cursor.getColumnIndex(C_TAG_SENTSERVER_TIME);

.

如何测试字符串是否为有效的 Joda DateTime。字符串例如11236263722,基本上是长的。

我想检查字符串是否不是例如“,kjj”,因为这将是无效的。

我尝试了以下方法。

public boolean isValidDate(String dateString) {

        Log.e(TAG, "dateString (sentToServerTime under test) =========>>>>>>>> " + dateString);

            if(DateTime.parse(dateString) != null){

                Log.e(TAG, "sent to server time is valid");
                return true;

            }else{

                Log.e(TAG, "sent to server time is not valid");
                return false;

            }

    }

【问题讨论】:

    标签: android date datetime time jodatime


    【解决方案1】:

    我不知道“11236263722”是什么格式。它是自 1970 年以来的秒数还是毫秒数???它看起来不像这样。无论如何,如果你只是想确保你有一个只有数字的“长”,那么遵循简单的方法对你来说可能就足够了。

    String test = "11236263722";
    
    public boolean isValid(String test) {
      for (int i = 0, n = test.length(); i < n; i++) {
        char c = test.charAt(i);
        if (c < '0' || c > '9') {
          return false;
        }
      }
      return true;
    }
    

    但如果您的日期字符串采用任何专门的日期/时间模式,那么您必须像这样指定the exact and expected pattern

      public boolean isValid(String test) {
        try {
          DateTimeFormatter dtf = DateTimeFormat.forPattern("{your pattern}");
          dtf.parseDateTime(text);
          return true;
        } catch (IllegalArgumentException iae) {
          return false;
        }
      }
    

    【讨论】:

    • 谢谢。是的,它是 1970 年的秒/毫秒。
    猜你喜欢
    • 2011-02-11
    • 2010-12-23
    • 2013-02-13
    • 2011-06-17
    • 1970-01-01
    • 2011-11-26
    • 2018-03-21
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多