Table of Contents
1. Introduction
2. Introduction to knowledge points
3. Explanation of knowledge points
1. Declaration of Date class
2. Common methods of the Date class
3. SimpleDateFormat format date
Home Java javaTutorial Introduction to methods and usage of using Date and SimpleDateFormat classes to process time in Java

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

Apr 21, 2023 pm 03:01 PM
java date simpledateformat

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+"=============");

}
}
Copy after login

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+"=============");
}
}
Copy after login

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));
}
}
Copy after login

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());// 将当前日期进行格式化操作
}
}
Copy after login

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+"=============");

}
}
Copy after login

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+"=============");
}
}
Copy after login

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 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

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)
2 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

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)

Square Root in Java Square Root in Java Aug 30, 2024 pm 04:26 PM

Guide to Square Root in Java. Here we discuss how Square Root works in Java with example and its code implementation respectively.

Perfect Number in Java Perfect Number in Java Aug 30, 2024 pm 04:28 PM

Guide to Perfect Number in Java. Here we discuss the Definition, How to check Perfect number in Java?, examples with code implementation.

Random Number Generator in Java Random Number Generator in Java Aug 30, 2024 pm 04:27 PM

Guide to Random Number Generator in Java. Here we discuss Functions in Java with examples and two different Generators with ther examples.

Weka in Java Weka in Java Aug 30, 2024 pm 04:28 PM

Guide to Weka in Java. Here we discuss the Introduction, how to use weka java, the type of platform, and advantages with examples.

Armstrong Number in Java Armstrong Number in Java Aug 30, 2024 pm 04:26 PM

Guide to the Armstrong Number in Java. Here we discuss an introduction to Armstrong's number in java along with some of the code.

Smith Number in Java Smith Number in Java Aug 30, 2024 pm 04:28 PM

Guide to Smith Number in Java. Here we discuss the Definition, How to check smith number in Java? example with code implementation.

Java Spring Interview Questions Java Spring Interview Questions Aug 30, 2024 pm 04:29 PM

In this article, we have kept the most asked Java Spring Interview Questions with their detailed answers. So that you can crack the interview.

Break or return from Java 8 stream forEach? Break or return from Java 8 stream forEach? Feb 07, 2025 pm 12:09 PM

Java 8 introduces the Stream API, providing a powerful and expressive way to process data collections. However, a common question when using Stream is: How to break or return from a forEach operation? Traditional loops allow for early interruption or return, but Stream's forEach method does not directly support this method. This article will explain the reasons and explore alternative methods for implementing premature termination in Stream processing systems. Further reading: Java Stream API improvements Understand Stream forEach The forEach method is a terminal operation that performs one operation on each element in the Stream. Its design intention is

See all articles