Home>Article>Java> What are the methods to convert string to date in java

What are the methods to convert string to date in java

青灯夜游
青灯夜游 Original
2021-04-23 17:58:27 69621browse

Conversion method: 1. Use SimpleDateFormat to format time; 2. Use "org.apache.commons.lang3.time.DateUtils" to format time; 3. Use DateTimeFormatter to format time.

What are the methods to convert string to date in java

The operating environment of this tutorial: windows7 system, java8 version, DELL G3 computer.

There are three common ways to convert String to Date: SimpleDateFormat, org.apache.commons.lang3.time.DateUtils, DateTimeFormatter (Java 8)

Description
SimpleDateFormat Thread-unsafe, flexible text matching

DateUtils

Tool class, supports date operations
DateTimeFormatter

Thread safety, supports chain programming with LocalDateTime, Convenient comparison operations

The following is the sample code

/** * 指定当前时间-指定时间是否大于30秒 */ //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); } }

Related video tutorial recommendations:Java video tutorial

The above is the detailed content of What are the methods to convert string to date in java. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn