java 对任意形式字符串检查是否能转换为日期并转换为yyyy-MM-dd的形式

在需要将字符串转换为日期时,有时并不能完全固定输入的字符串格式,或者需要对其进行校验,比如excel导入功能等,而日期转换是需要特定格式的字符串输入的,这就需要我们提前对字符串进行校验和转化.

以下对一些常用格式的日期字符串进行了检查,并判断了年月日的数目是否正确,直接调用managerDate(str)即可,其中纯数字字符串必须是八位才符合条件,日期分割符为 ‘年’,‘月’,‘日’,’-’,’/’,’\’,’.’,’*'中的一个,需要补充可以对pattern1进行修改

public static String managerDate(String value){
        String result = "";

        String pattern1 = "^\\d{4}(年|-|/|\\.|\\\\|\\*)(0?[1-9]|1[0-2])(月|-|/|\\.|\\\\|\\*)((0?[1-9])|((1|2)[0-9])|30|31)(日|)$";
        String pattern2 = "^\\d{4}(0?[1-9]|1[0-2])((0?[1-9])|((1|2)[0-9])|30|31)$";

        Pattern r1 = Pattern.compile(pattern1);
        Matcher m1 = r1.matcher(value);
        Pattern r2 = Pattern.compile(pattern2);
        Matcher m2 = r2.matcher(value);
        if(m1.matches()){
            result = value.replaceAll("(年|月|-|/|\\.|\\\\|\\*)","-");
            result = result.replaceAll("日","");
        }else if(m2.matches()){
            if(value.length() != 8){
                throw new ResultException("日期格式不正确,请检查!");
            }
            result = value.substring(0,4) + "-" + value.substring(4,6) + "-" + value.substring(6);
        }else{
            throw new ResultException("日期格式不正确,请检查!");
        }

        String[] dateArr = result.split("-");
        int year = Integer.valueOf(dateArr[0]);
        int month = Integer.valueOf(dateArr[1]);
        int day = Integer.valueOf(dateArr[2]);
        int[] monthLengths = new int[]{0, 31, -1, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
        if(isLeapYear(year)){
            monthLengths[2] = 29;
        }else{
            monthLengths[2] = 28;
        }
        int monthLength = monthLengths[month];
        if(day>monthLength){
            throw new ResultException("日期格式不正确,请检查!");
        }

        result = year + "-" + ("0" + month).substring(("0" + month).length() - 2) + "-" + ("0" + day).substring(("0" + day).length() - 2);

        return result;
    }

	private static boolean isLeapYear(int year){
        return ((year % 4 == 0 && year % 100 != 0) || year % 400 == 0) ;
    }

注: 里面的抛出异常请替换为自己适合的方式;想要另外的格式可以修改最后的result拼接,也可以将其改为传入分隔符参数的方式增加其通用性(java小白,如果有其它更好的方法或者建议,欢迎评论)

### 回答1: 可以使用Java标准库中的日期时间类(java.time包)来解析任意时间字符串。 以下是一个示例代码,它演示了如何使用java.time中的类将任意格式的时间字符串解析为LocalDateTime对象: ``` import java.time.LocalDateTime; import java.time.format.DateTimeFormatter; public class DateTimeParser { public static void main(String[] args) { String dateTimeString = "2021-09-01 10:30:15"; DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"); LocalDateTime dateTime = LocalDateTime.parse(dateTimeString, formatter); System.out.println("Parsed datetime: " + dateTime); } } ``` 在上述代码中,首先定义了一个要解析的时间字符串,然后使用DateTimeFormatter类创建了一个格式化器对象。这个格式化器对象指定了时间字符串的格式,即"yyyy-MM-dd HH:mm:ss",其中: - yyyy表示年份 - MM表示月份 - dd表示日期 - HH表示小时(24小时制) - mm表示分钟 - ss表示秒 然后,调用LocalDateTime类的parse方法,将时间字符串和格式化器对象作为参数传递进去,即可得到一个LocalDateTime对象,该对象包含了解析后的日期和时间信息。最后,可以将这个LocalDateTime对象打印出来,以确认解析结果是否正确。 需要注意的是,如果时间字符串的格式与指定的格式化器对象不匹配,会抛出DateTimeParseException异常。因此,使用时需要确保时间字符串的格式和格式化器对象的格式一致。 ### 回答2: Java解析任意时间字符串可以使用SimpleDateFormat类或DateTimeFormatter类中的方法。下面是使用SimpleDateFormat类的示例代码: ```java import java.text.SimpleDateFormat; import java.util.Date; public class TimeParser { public static void main(String[] args) throws Exception { String dateString = "2021-09-20 13:30:45"; SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); Date date = format.parse(dateString); System.out.println(date); } } ``` 在上面的代码中,首先定义了一个时间字符串"2021-09-20 13:30:45",然后创建了一个SimpleDateFormat对象,指定了日期格式"yyyy-MM-dd HH:mm:ss",接着调用parse方法将时间字符串解析成Date对象,最后打印出解析后的日期对象。 上述代码的输出结果为Mon Sep 20 13:30:45 GMT+08:00 2021,表示已成功将时间字符串解析成Date对象。 需要注意的是,SimpleDateFormat是线程不安全的,如果在多线程环境下使用,建议使用ThreadLocal来保证每个线程拥有独立的SimpleDateFormat对象。 此外,还可以使用DateTimeFormatter类来解析时间字符串,DateTimeFormatter类是Java 8提供的日期和时间格式化工具类。 ```java import java.time.LocalDateTime; import java.time.format.DateTimeFormatter; public class TimeParser { public static void main(String[] args) { String dateString = "2021-09-20 13:30:45"; DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"); LocalDateTime dateTime = LocalDateTime.parse(dateString, formatter); System.out.println(dateTime); } } ``` 上述代码中,首先定义了一个时间字符串"2021-09-20 13:30:45",然后创建了一个DateTimeFormatter对象,指定了日期格式"yyyy-MM-dd HH:mm:ss",接着调用parse方法将时间字符串解析成LocalDateTime对象,最后打印出解析后的日期时间对象。 上述代码的输出结果为2021-09-20T13:30:45,表示已成功将时间字符串解析成LocalDateTime对象。 使用DateTimeFormatter类的好处是它是线程安全的,可以在多线程环境下使用,而且支持更多的日期和时间格式化选项。 综上所述,可以通过使用SimpleDateFormat类或DateTimeFormatter类中的方法来解析任意时间字符串。 ### 回答3: 在Java中,我们可以使用SimpleDateFormat类来解析任意时间字符串。这个类提供了一种简单而灵活的方式来解析和格式化日期和时间。 首先,我们需要创建一个SimpleDateFormat对象,并指定日期时间的格式。例如,如果我们要解析的时间字符串是"2022-09-18 12:30:45",我们可以使用下面的代码来创建SimpleDateFormat对象: SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); 接下来,我们可以使用SimpleDateFormat对象的parse()方法来解析时间字符串。该方法接收一个时间字符串作为参数,并返回一个Date对象。例如,我们可以使用以下代码将字符串解析为日期对象: try { Date date = sdf.parse("2022-09-18 12:30:45"); System.out.println(date); } catch (ParseException e) { e.printStackTrace(); } 在这个例子中,我们使用try-catch块来捕获可能抛出的ParseException异常。 最后,我们可以使用Date对象来执行各种日期和时间操作,例如获取年份、月份、日等。我们还可以使用SimpleDateFormat对象的format()方法将Date对象格式化为我们想要的时间字符串。 总结一下,要解析任意时间字符串,我们可以使用SimpleDateFormat类来指定时间格式并解析时间字符串。这样,我们就可以将时间字符串转换为Date对象,并可以对其执行各种日期和时间操作。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值