轉換方法:1、使用SimpleDateFormat來格式化時間;2、使用「org.apache.commons.lang3.time.DateUtils」格式化時間;3、使用DateTimeFormatter來格式化時間。
本教學操作環境:windows7系統、java8版、DELL G3電腦。
String轉Date常見三種方式:SimpleDateFormat、org.apache.commons.lang3.time.DateUtils、DateTimeFormatter(Java 8)
#SimpleDateFormat | |
##DateUtils | 工具類別、支援日期運算 |
DateTimeFormatter | 執行緒安全性、配合LocalDateTime支援鍊式程式設計、方便比較運算 |
下面為範例程式碼
/** * 指定当前时间-指定时间是否大于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); } }相關影片教學推薦:Java影片教學# ##
以上是java中將string轉為date的方法有哪些的詳細內容。更多資訊請關注PHP中文網其他相關文章!
陳述
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn

熱AI工具

Undresser.AI Undress
人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover
用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool
免費脫衣圖片

Clothoff.io
AI脫衣器

AI Hentai Generator
免費產生 AI 無盡。

熱門文章
R.E.P.O.能量晶體解釋及其做什麼(黃色晶體)
1 個月前By尊渡假赌尊渡假赌尊渡假赌
R.E.P.O.最佳圖形設置
1 個月前By尊渡假赌尊渡假赌尊渡假赌
刺客信條陰影:貝殼謎語解決方案
2 週前ByDDD
R.E.P.O.如果您聽不到任何人,如何修復音頻
1 個月前By尊渡假赌尊渡假赌尊渡假赌
R.E.P.O.聊天命令以及如何使用它們
1 個月前By尊渡假赌尊渡假赌尊渡假赌

熱工具

WebStorm Mac版
好用的JavaScript開發工具

記事本++7.3.1
好用且免費的程式碼編輯器

EditPlus 中文破解版
體積小,語法高亮,不支援程式碼提示功能

SublimeText3漢化版
中文版,非常好用

VSCode Windows 64位元 下載
微軟推出的免費、功能強大的一款IDE編輯器