search
HomeJavajavaTutorialIntroduction to methods and usage of using Date and SimpleDateFormat classes to process time in Java

1. Introduction

The Date class in the java.util package represents a specific time, accurate to milliseconds. If we want to use our Date class, then we must introduce our Date class.

Writing the year directly into the Date class will not get the correct result. Because Date in Java is calculated from 1900, so as long as you fill in the first parameter with the number of years since 1900, you will get the year you want. The month needs to be subtracted by 1, and the day can be inserted directly. This method is rarely used, and the second method is commonly used.

This method is to convert a string that conforms to a specific format, such as yyyy-MM-dd, into Date type data. First, define a Date type object Date date = null; Then define a String type string that conforms to the format String dateStr = "2010-9-10"; Split this string dateDivide = dateStr.split("- "); Take out the year, month and day respectively and assign them to Calendar. Use Calendar's getTime(); to obtain the date and assign it to date.

2. Introduction to knowledge points

  • 1. Declaration of Date class

  • 2. Common methods of Date class

  • 3. SimpleDateFormat formatted date

3. Explanation of knowledge points

1. Declaration of Date class

If we want to get the date and time, we can instantiate the Date class

(1) Get the current date and time

Date d=new Date();

(2) Obtain the specified date and time

Date d=new Date(long date);

Note: To get the long date of the current time, we can use the getTime(); method

Code demonstration:

package Test2;
import java.util.Date;
public class Tested {
private final static String name = "磊哥的java历险记-@51博客";

public static void main(String args[]){
//产生日期对象
Date d=new Date();
System.out.println(d);
//获取时间为长整型,时间戳
long l=d.getTime();
System.out.println(l);
Date d1=new Date(l);
System.out.println(d1);
System.out.println("============="+name+"=============");

}
}

Introduction to methods and usage of using Date and SimpleDateFormat classes to process time in Java

2. Common methods of the Date class

  • (1) getYear()//Year, the value after subtracting 1900 from the year in the Date object, so the corresponding year needs to be displayed Then you need to add 1900

  • to the return value (2) getMonth()//Month, the Date class stipulates that January is 0, February is 1, and March is 2 , and so on for subsequent steps.

  • (3)getDate()//Date

  • (4)getHours()//Hour

  • (5)getMinutes()//Minutes

  • (6)getSeconds()//Seconds

  • (7)getDay ()//Week of the week, the Date class stipulates that Sunday is 0, Monday is 1, Tuesday is 2, and so on.

Code demonstration:

package Test2;
//导入时间包
import java.util.Date;
public class Tested {
private final static String name = "磊哥的java历险记-@51博客";
public static void main(String args[]){
//创建时间对象
Date d2 = new Date();
//年份,Java中的Date表示的是自1900年以来所经过的时间
int year = d2.getYear() + 1900;
//月份,最后一个月取决于一年中的月份数。 因为这个值的初始值是0,因此我们要用它来表示正确的月份时就需要加1。
int month = d2.getMonth() + 1;
//日期
int date = d2.getDate();
//小时
int hour = d2.getHours();
//分钟
int minute = d2.getMinutes();
//秒
int second = d2.getSeconds();
//星期几
int day = d2.getDay();
System.out.println("年份:" + year);
System.out.println("月份:" + month);
System.out.println("日期:" + date);
System.out.println("小时:" + hour);
System.out.println("分钟:" + minute);
System.out.println("秒:" + second);
System.out.println("星期:" + day);
System.out.println("============="+name+"=============");
}
}

Introduction to methods and usage of using Date and SimpleDateFormat classes to process time in Java

3. SimpleDateFormat format date

SimpleDateFormat Is a class for formatting and parsing dates in a locale-sensitive manner. SimpleDateFormat allows you to choose any user-defined date-time format to run on.

(1) SimpleDateFormate initialization:

SimpleDateFormate sdf=new SimpleDateFormate (date format);

Note: Date format

(2) SimpleDateFormat common methods:

  • ## format(Date d):Convert date format to string Data

  • parse(String s):Convert string format to date data

Code demonstration :

package Test2;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
class Person extends Object{
public static void main(String args[]){
Date d=new Date();
//传入指定时间格式
SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");
//日期格式化输出
System.out.println(sdf.format(d));
}
}

Introduction to methods and usage of using Date and SimpleDateFormat classes to process time in Java

Define a tool class:

package Test2;
//导入时间包import java.text.SimpleDateFormat;
import java.util.Date;
public class MyDate {
private final static String name = "磊哥的java历险记-@51博客";
// 定义的MyDateDemo类
private SimpleDateFormat sd = null;
// 声明SimpleDateFormat对象sd
public String getDate01() {
// 定义getDate01方法
this.sd = new SimpleDateFormat("yyyy-MM-dd HH:mm;ss.sss"); // 得到一个"yyyy-MM-dd
// HH:mm;ss.sss"格式日期
return this.sd.format(new Date());
// 将当前日期进行格式化操作
}
public String getDate02() { // 定义getDate02方法
this.sd = new SimpleDateFormat("yyyy年MM月dd日 HH时mm分ss秒sss毫秒");
// 得到一个"yyyy年MM月dd日
//HH时mm分ss秒sss毫秒"格式日期
return this.sd.format(new Date()); // 将当前日期进行格式化操作 }
public String getDate03() {// 定义getDate03方法
this.sd = new SimpleDateFormat("yyyyMMddHHmmsssss");
// 得到一个"yyyyMMddHHmmsssss"格式日期(也就是时间戳)
return this.sd.format(new Date());// 将当前日期进行格式化操作
}
}

Main method call:

package com.Test;
import Test2.MyDate;
import java.util.Date;
public class Main {

private final static String name = "磊哥的java历险记-@51博客";

public static void main(String[] args) { // 主方法
MyDate dd = new MyDate(); // 声明dd对象,并实例化
System.out.println("默认日期格式: " + new Date());
// 分别调用方法输入不同格式的日期
System.out.println("英文日期格式: " + dd.getDate01());
System.out.println("中文日期格式: " + dd.getDate02());
System.out.println("时间戳: " + dd.getDate03());
System.out.println("============="+name+"=============");

}
}

Introduction to methods and usage of using Date and SimpleDateFormat classes to process time in Java

4. Refining Exercise

4.1 Question
  • (1) Get the current date and print out yyyy -MM-dd hh:mm:ss format

  • (2) Get the year and month of the current date and output it

4.2 Experiment Steps
  • (1) Use the date object to get the current date

  • (2) Use simpleDateFormat to format the date

  • (3) Use the common method of date to obtain the year and month

4.3 Code Demonstration
package com.Test;
import Test2.MyDate;
import java.text.SimpleDateFormat;
import java.util.Date;
public class Main {
private final static String name = "磊哥的java历险记-@51博客";
public static void main(String[] args) { // 主方法
//获取当前日期
Date d2=new Date();
//转换为yyyy-MM-dd hh:mm:ss
SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
//日期格式化
System.out.println("日期格式化:"+sdf.format(d2));
int year = d2.getYear() + 1900;//年份
int month = d2.getMonth() + 1;//月份
System.out.println("年份:" + year);
System.out.println("月份:" + month);
System.out.println("============="+name+"=============");
}
}

Introduction to methods and usage of using Date and SimpleDateFormat classes to process time in Java

The above is the detailed content of Introduction to methods and usage of using Date and SimpleDateFormat classes to process time in Java. For more information, please follow other related articles on the PHP Chinese website!

Statement
This article is reproduced at:亿速云. If there is any infringement, please contact admin@php.cn delete
How do I use Maven or Gradle for advanced Java project management, build automation, and dependency resolution?How do I use Maven or Gradle for advanced Java project management, build automation, and dependency resolution?Mar 17, 2025 pm 05:46 PM

The article discusses using Maven and Gradle for Java project management, build automation, and dependency resolution, comparing their approaches and optimization strategies.

How do I create and use custom Java libraries (JAR files) with proper versioning and dependency management?How do I create and use custom Java libraries (JAR files) with proper versioning and dependency management?Mar 17, 2025 pm 05:45 PM

The article discusses creating and using custom Java libraries (JAR files) with proper versioning and dependency management, using tools like Maven and Gradle.

How do I implement multi-level caching in Java applications using libraries like Caffeine or Guava Cache?How do I implement multi-level caching in Java applications using libraries like Caffeine or Guava Cache?Mar 17, 2025 pm 05:44 PM

The article discusses implementing multi-level caching in Java using Caffeine and Guava Cache to enhance application performance. It covers setup, integration, and performance benefits, along with configuration and eviction policy management best pra

How can I use JPA (Java Persistence API) for object-relational mapping with advanced features like caching and lazy loading?How can I use JPA (Java Persistence API) for object-relational mapping with advanced features like caching and lazy loading?Mar 17, 2025 pm 05:43 PM

The article discusses using JPA for object-relational mapping with advanced features like caching and lazy loading. It covers setup, entity mapping, and best practices for optimizing performance while highlighting potential pitfalls.[159 characters]

How does Java's classloading mechanism work, including different classloaders and their delegation models?How does Java's classloading mechanism work, including different classloaders and their delegation models?Mar 17, 2025 pm 05:35 PM

Java's classloading involves loading, linking, and initializing classes using a hierarchical system with Bootstrap, Extension, and Application classloaders. The parent delegation model ensures core classes are loaded first, affecting custom class loa

See all articles

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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Chat Commands and How to Use Them
1 months agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)