有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

日期Java SimpleDataFormat使用带有jolly字符的模式

有没有一种方法可以用包含一些“特殊字符”或“jolly字符”作为分隔符的模式来解析日期,并使用标准SimpleDataFormat?我想使用模式"yyyy MM dd""yyyy/MM/dd""yyyy-MM-dd"等等来解析我的日期。。。,所以我在搜索类似“yyyy*MM*dd”的东西,其中*是一个特殊字符,意思是“随机字符”

SimpleDateFormat fmt = new SimpleDateFormat("yyyy-MM-dd");
Date d = fmt.parse(stringdate);

共 (3) 个答案

  1. # 1 楼答案

    你应该试试这个

     String pattern = "yyyy-MM-dd";
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat(pattern);
    
        String date = simpleDateFormat.format(new Date());
        System.out.println(date);
    
  2. # 2 楼答案

    使用正则表达式过滤掉有趣的字符,然后解析过滤后的字符串

    String stringdate = "2017x01-18"; 
    SimpleDateFormat fmt = new SimpleDateFormat("yyyy-MM-dd", Locale.ENGLISH);
    Date d = fmt.parse(Pattern.compile("(....).(..).(..)").matcher(stringdate).replaceAll("$1-$2-$3"));
    
  3. # 3 楼答案

    您可以尝试将输入“标准化”为所需格式:

    SimpleDateFormat fmt = new SimpleDateFormat("yyyy-MM-dd");
    fmt.parse(stringdate.replaceAll(" ", "-").replaceAll("/","-"));