Table of Contents
3.使用parse()方法将字符串转换为日期
Home Java javaTutorial Introduction to the usage of SimpleDateFormat in Java (code example)

Introduction to the usage of SimpleDateFormat in Java (code example)

Feb 19, 2019 pm 03:56 PM
in java

本篇文章给大家带来的内容是关于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
    }
}
Copy after login

此时我们会发现, 输出的格式并不是我们预期的格式,一般情况下,我们希望的格式都是类似于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等,自定义格式如下表所示:

格式释义举例
yyyy2019
MM02
dd18
HH小时(24小时制)13,下午一点
mm分钟53
ss42
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
    }
}
Copy after login

3.使用parse()方法将字符串转换为日期

在实际开发过程中,我们经常需要将字符串转换为日期类型,以进行后续操作,此时可以使用parse()

方法,但需要注意:如果字符串与指定的格式不匹配,会报java.text.ParseException异常

![snipaste_20190218_141555](E:\临时\20190218\snipaste_20190218_141555.png)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();
        }
    }
}
Copy after login

运行结果如下图所示:
Introduction to the usage of SimpleDateFormat in Java (code example)
由此我们可以看到,strDate1格式匹配能正常转换为Date类型,而strDate2由于格式不匹配,抛出java.text.ParseException,正是因为如此,以上的代码才必须包括在try,catch语句中,否则IDEA会提示错误,代码也编译不通过,如下图所示:
Introduction to the usage of SimpleDateFormat in Java (code example)

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!

Statement of this Website
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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

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

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Is the company's security software causing the application to fail to run? How to troubleshoot and solve it? Is the company's security software causing the application to fail to run? How to troubleshoot and solve it? Apr 19, 2025 pm 04:51 PM

Troubleshooting and solutions to the company's security software that causes some applications to not function properly. Many companies will deploy security software in order to ensure internal network security. ...

How to simplify field mapping issues in system docking using MapStruct? How to simplify field mapping issues in system docking using MapStruct? Apr 19, 2025 pm 06:21 PM

Field mapping processing in system docking often encounters a difficult problem when performing system docking: how to effectively map the interface fields of system A...

How to elegantly obtain entity class variable names to build database query conditions? How to elegantly obtain entity class variable names to build database query conditions? Apr 19, 2025 pm 11:42 PM

When using MyBatis-Plus or other ORM frameworks for database operations, it is often necessary to construct query conditions based on the attribute name of the entity class. If you manually every time...

How do I convert names to numbers to implement sorting and maintain consistency in groups? How do I convert names to numbers to implement sorting and maintain consistency in groups? Apr 19, 2025 pm 11:30 PM

Solutions to convert names to numbers to implement sorting In many application scenarios, users may need to sort in groups, especially in one...

How does IntelliJ IDEA identify the port number of a Spring Boot project without outputting a log? How does IntelliJ IDEA identify the port number of a Spring Boot project without outputting a log? Apr 19, 2025 pm 11:45 PM

Start Spring using IntelliJIDEAUltimate version...

How to safely convert Java objects to arrays? How to safely convert Java objects to arrays? Apr 19, 2025 pm 11:33 PM

Conversion of Java Objects and Arrays: In-depth discussion of the risks and correct methods of cast type conversion Many Java beginners will encounter the conversion of an object into an array...

E-commerce platform SKU and SPU database design: How to take into account both user-defined attributes and attributeless products? E-commerce platform SKU and SPU database design: How to take into account both user-defined attributes and attributeless products? Apr 19, 2025 pm 11:27 PM

Detailed explanation of the design of SKU and SPU tables on e-commerce platforms This article will discuss the database design issues of SKU and SPU in e-commerce platforms, especially how to deal with user-defined sales...

How to elegantly get entity class variable name building query conditions when using TKMyBatis for database query? How to elegantly get entity class variable name building query conditions when using TKMyBatis for database query? Apr 19, 2025 pm 09:51 PM

When using TKMyBatis for database queries, how to gracefully get entity class variable names to build query conditions is a common problem. This article will pin...

See all articles