本篇文章给大家带来的内容是关于Java中SimpleDateFormat的用法介绍(代码示例),有一定的参考价值,有需要的朋友可以参考一下,希望对你有所帮助。
1、为什么要使用SimpleDateFormat?
在Java中,如果我们想获取当前时间,一般会使用Date类的无参构造函数,如下所示,我们获取到当前时间并输出:
import java.util.Date; public class SimpleDateFormatDemo { public static void main(String[] args) { Date currentTime = new Date(); System.out.println(currentTime); // 输出:Mon Feb 18 10:24:30 CST 2019 } }
此时我们会发现, 输出的格式并不是我们预期的格式,一般情况下,我们希望的格式都是类似于2019-02-18,2019-02-18 10:24:30,2019/02/18这样的,此时我们就需要用到java.text.SimpleDateFormat来自定义格式。
2.使用format()方法将日期转换为字符串
使用format()方法,我们可以将日期类型转换为自己自定义的字符串格式,如2019-02-18,2019/02/18,2019-02-18 10:24:30等,自定义格式如下表所示:
格式 | 释义 | 举例 |
---|---|---|
yyyy | 年 | 2019 |
MM | 月 | 02 |
dd | 日 | 18 |
HH | 小时(24小时制) | 13,下午一点 |
mm | 分钟 | 53 |
ss | 秒 | 42 |
SSS | 毫秒 | 629 |
package com.zwwhnly.springbootdemo; import java.text.SimpleDateFormat; import java.util.Date; public class SimpleDateFormatDemo { public static void main(String[] args) { Date currentTime = new Date(); System.out.println(currentTime); // Mon Feb 18 13:53:50 CST 2019 SimpleDateFormat simpleDateFormat1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS"); SimpleDateFormat simpleDateFormat2 = new SimpleDateFormat("yyyy-MM-dd"); SimpleDateFormat simpleDateFormat3 = new SimpleDateFormat("yyyy/MM/dd"); System.out.println(simpleDateFormat1.format(currentTime)); // 输出2019-02-18 13:53:50.629 System.out.println(simpleDateFormat2.format(currentTime)); // 输出2019-02-18 System.out.println(simpleDateFormat3.format(currentTime)); // 输出2019/02/18 } }
3.使用parse()方法将字符串转换为日期
在实际开发过程中,我们经常需要将字符串转换为日期类型,以进行后续操作,此时可以使用parse()
方法,但需要注意:如果字符串与指定的格式不匹配,会报java.text.ParseException异常。
package com.zwwhnly.springbootdemo; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; public class SimpleDateFormatDemo { public static void main(String[] args) { try { SimpleDateFormat simpleDateFormat1 = new SimpleDateFormat("yyyy-MM-dd HH:mm"); String strDate1 = "2019-02-18 13:58"; String strDate2 = "2019-02-18"; Date date1 = simpleDateFormat1.parse(strDate1); System.out.println(date1); Date date2 = simpleDateFormat1.parse(strDate2); System.out.println(date2); } catch (ParseException e) { e.printStackTrace(); } } }
运行结果如下图所示:
由此我们可以看到,strDate1格式匹配能正常转换为Date类型,而strDate2由于格式不匹配,抛出java.text.ParseException,正是因为如此,以上的代码才必须包括在try,catch语句中,否则IDEA会提示错误,代码也编译不通过,如下图所示:
The above is the detailed content of Introduction to the usage of SimpleDateFormat in Java (code example). For more information, please follow other related articles on the PHP Chinese website!

Java is widely used in enterprise-level applications because of its platform independence. 1) Platform independence is implemented through Java virtual machine (JVM), so that the code can run on any platform that supports Java. 2) It simplifies cross-platform deployment and development processes, providing greater flexibility and scalability. 3) However, it is necessary to pay attention to performance differences and third-party library compatibility and adopt best practices such as using pure Java code and cross-platform testing.

JavaplaysasignificantroleinIoTduetoitsplatformindependence.1)Itallowscodetobewrittenonceandrunonvariousdevices.2)Java'secosystemprovidesusefullibrariesforIoT.3)ItssecurityfeaturesenhanceIoTsystemsafety.However,developersmustaddressmemoryandstartuptim

ThesolutiontohandlefilepathsacrossWindowsandLinuxinJavaistousePaths.get()fromthejava.nio.filepackage.1)UsePaths.get()withSystem.getProperty("user.dir")andtherelativepathtoconstructthefilepath.2)ConverttheresultingPathobjecttoaFileobjectifne

Java'splatformindependenceissignificantbecauseitallowsdeveloperstowritecodeonceandrunitonanyplatformwithaJVM.This"writeonce,runanywhere"(WORA)approachoffers:1)Cross-platformcompatibility,enablingdeploymentacrossdifferentOSwithoutissues;2)Re

Java is suitable for developing cross-server web applications. 1) Java's "write once, run everywhere" philosophy makes its code run on any platform that supports JVM. 2) Java has a rich ecosystem, including tools such as Spring and Hibernate, to simplify the development process. 3) Java performs excellently in performance and security, providing efficient memory management and strong security guarantees.

JVM implements the WORA features of Java through bytecode interpretation, platform-independent APIs and dynamic class loading: 1. Bytecode is interpreted as machine code to ensure cross-platform operation; 2. Standard API abstract operating system differences; 3. Classes are loaded dynamically at runtime to ensure consistency.

The latest version of Java effectively solves platform-specific problems through JVM optimization, standard library improvements and third-party library support. 1) JVM optimization, such as Java11's ZGC improves garbage collection performance. 2) Standard library improvements, such as Java9's module system reducing platform-related problems. 3) Third-party libraries provide platform-optimized versions, such as OpenCV.

The JVM's bytecode verification process includes four key steps: 1) Check whether the class file format complies with the specifications, 2) Verify the validity and correctness of the bytecode instructions, 3) Perform data flow analysis to ensure type safety, and 4) Balancing the thoroughness and performance of verification. Through these steps, the JVM ensures that only secure, correct bytecode is executed, thereby protecting the integrity and security of the program.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Dreamweaver CS6
Visual web development tools

PhpStorm Mac version
The latest (2018.2.1) professional PHP integrated development tool

WebStorm Mac version
Useful JavaScript development tools

Notepad++7.3.1
Easy-to-use and free code editor

Atom editor mac version download
The most popular open source editor
