What are the ways to convert string to date in Java, and how to implement it

This article shares with you the method of converting string to date in Java. There are three common ways to convert String to Date, namely SimpleDateFormat, org.apache.commons.lang3.time.DateUtils, and DateTimeFormatter. Next, we will understand Take a look at how these methods implement string to date conversion.

/**
     *     Specifies the current time - whether the specified time is greater than 30 seconds
     */
    
    //SimpleDateFormat
    private static void m1() throws ParseException {
        String endTime = "哈哈2020-02-07 18:58:02.0你好";//支持特殊格式转换
        String format = "哈哈yyyy-MM-dd HH:mm:ss";
        SimpleDateFormat sdf = new SimpleDateFormat(format);
        Date edate = sdf.parse(endTime);
        Date now = new Date();
        String nowStr = DateFormatUtils.format(now, format);
        if(DateUtils.addSeconds(edate, 30).before((now))){
            logger.info("true endTime={} now={}",endTime, nowStr);
        }else{
            logger.info("false endTime={} now={}",endTime, nowStr);
        }
    }
    //DateUtils
    private static void m3() throws ParseException {
        String endTime = "2020-02-07 18:58:02.0";
        String format = "yyyy-MM-dd HH:mm:ss";
        Date edate = DateUtils.parseDate(endTime, format, "yyyy-MM-dd HH:mm:ss.SSS");//支持多格式匹配
        Date now = new Date();
        String nowStr = DateFormatUtils.format(now, format);
        if(DateUtils.addSeconds(edate, 30).before((now))){
            logger.info("true endTime={} now={}",endTime, nowStr);
        }else{
            logger.info("false endTime={} now={}",endTime, nowStr);
        }
    }
    //DateTimeFormatter
    private static void m2(){
        String endTime = "2020-02-07 18:58:02";
        String format = "yyyy-MM-dd HH:mm:ss";
        LocalDateTime now = LocalDateTime.now();
        DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern(format);
        String nowStr = now.format(dateTimeFormatter);
        if(LocalDateTime.parse(endTime, dateTimeFormatter)
                .plusSeconds(30).isBefore(LocalDateTime.now())){//链式编程
            logger.info("true endTime={} now={}",endTime, nowStr);
        }else{
            logger.info("false endTime={} now={}",endTime, nowStr);
        }
    }

Leave a Reply

Your email address will not be published. Required fields are marked *

en_USEnglish