Java - 如何检查值是否为Date类型

时间:2017-04-26 10:34:27

标签: java date

我有项目要求。 .txt中的值为 -

 02/01/2017 00:00:00

现在我需要一些规则来检查数据文件中的这个值是否为Date类型。我怎样才能做到这一点?谢谢。我是Java的新手,所以任何帮助都非常感谢。感谢

7 个答案:

答案 0 :(得分:1)

尝试解析它到目前为止。如果它抛出ParseException,那么它不是日期。

String dateString = "02/01/2017 00:00:00";
DateFormat df = new SimpleDateFormat("MM/dd/yyyy hh:mm:ss"); 
Date date;
try {
    date = df.parse(dateString);
} catch (ParseException e) {
    e.printStackTrace();
}

答案 1 :(得分:1)

如果您只想要有效的日子,请使用非宽松的解析:

String dateString = "02/28/2017 00:00:00";

DateFormat df = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss");
df.setLenient(false);
Date date;
try {
    date = df.parse(dateString);
    System.out.println(date);
} catch (ParseException e) {
    e.printStackTrace();
}

这会对像2月31日这样的非现有日子抛出异常

答案 2 :(得分:1)

  1. 方法一

    {
        "_index": "packets-2021-03-03",
        "_type": "doc",
        "_score": null,
        "_source": {
          "layers": {
            "frame": {
              "frame.interface_id": "0",
              "frame.interface_id_tree": {
                "frame.interface_name": "\\Device\\NPF_{AAAAAAAA}"
              },
              "frame.encap_type": "1",
              "frame.time": "Mar  3, 2021 12:41:47.06"
            },
            "eth": {
              "eth.dst": "AA:44:AA:AA:aa:AA",
              "eth.dst_tree": {
                "eth.dst_resolved": "ABCABC"
              },
              "eth.src": "aaaaaaaaaa",
              "eth.src_tree": {
                "eth.src_resolved": "testtest",
              },
              "eth.type": "0x00000800"
            },
            "ip": {
              "ip.version": "4"
              },
              "ip.len": "63",
              },
              "ip.frag_offset": "0"
            },
            "tcp": {
              "tcp.srcport": "2404"
              },
              "tcp.window_size_value": "20198",
              "tcp.analysis": {
                "tcp.analysis.push_bytes_sent": "23"
              },
              "Timestamps": {
                "tcp.time_relative": "545.993115000",
              },
              "tcp.payload": "00:15:2e:00:0c:00:1e:01:03:00:03:00:0b:00:00:00:8d:b7:29:8c:23:03:0e",
              "tcp.pdu.size": "23"
            },
            "tcp": {
              "tcp_asdu.start": "0x00000068",
            },
            "tcp_asdu": {
              "tcp_asdu.typeid": "30"
              "IOA: 11": {
                "tcp_asdu.ioa": "11"
                },
                "tcp_asdu.cp56time": "Mar  3, 2021 11:41:46.98",
                "tcp_asdu.cp56time_tree": {
                  "tcp_asdu.cp56time.ms": "46989"
                }
              }
            }
          }
        }
      }
    {
        *Another JSON string starts here*
    }
    
  2. 方法 2

    Date dt = new Date(); //this should your Dynamic object
    
    if (dt.getClass().equals(new Date().getClass())) 
    {
      //if its date object
    }
    

答案 3 :(得分:0)

用它来检查日期

String sDate1="31/12/1998 00:00:00";  
try{
  Date date1=new SimpleDateFormat("dd/MM/yyyy hh:mm:ss").parse(sDate1);  `
} 
catch(Exception e)
{
  //Not a date..
} 

答案 4 :(得分:0)

您可以使用正则表达式检查格式

public boolean isDate(String s){
String pattern= "([0-9]{2})/([0-9]{2})/([0-9]{4}) ([0-9]{2}):([0-9]{2}):([0-9]{2})";
return s.matches(pattern);}

答案 5 :(得分:0)

这是Java 8解决方案(当您使用ThreeTen Backport时,它也可以在Java 6和7中工作)。

private static final DateTimeFormatter DATE_TIME_FORMAT 
        = DateTimeFormatter.ofPattern("MM/dd/uuuu HH:mm:ss")
                .withResolverStyle(ResolverStyle.STRICT);

public static boolean hasTypeDate(String stringFromTxt) {
    try {
        DATE_TIME_FORMAT.parse(stringFromTxt);
        return true;
    } catch (DateTimeParseException dtpe) {
        return false;
    }
}

远离SimpleDateFormat获取新代码。它有时间,已经过时了一段时间。

如果您打算在第一天的某一天(如果02/01/2017表示1月2日),则需要格式模式dd/MM/uuuu HH:mm:ss

如果您需要知道.txt中的日期和时间,请使用:

        LocalDateTime dateTime = LocalDateTime.parse(stringFromTxt, DATE_TIME_FORMAT);

链接:ThreeTen Backport: java.time classes for Java 6 and 7

答案 6 :(得分:-1)

public static boolean isValidDate(String inDate) {
    SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
    dateFormat.setLenient(false);
    try {
      dateFormat.parse(inDate.trim());
    } catch (ParseException pe) {
      return false;
    }
    return true;
  }

public static void main(String[] args) {
 String file = "/path/to/your/file.txt";

try {

    BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(file)));
    String line;
    while ((line = br.readLine()) != null) {
        // do something with line
    }
    br.close();
   isValidDate(line));
   //do what you want :)
  }