Table of Contents
Date related classes
1.Date class
2.DateFormat class
3.Calendar class
Home Java javaTutorial Common uses of Java date classes

Common uses of Java date classes

Apr 23, 2023 pm 09:13 PM
java

1.Date class

Contains a Date class in the standard Java class library, its object represents a specific moment, accurate to milliseconds. When placing an order in the online mall and reviewing the reimbursement form, you need to obtain the current time, which can be accomplished through the Date class.

Example: Use of Date class

package li.normalclass.date;
 
import java.util.Date;
 
public class TestDate {
    public static void main(String[] args) {
        //获取当前的时间 格式为 yyyyMMddhhmmss
        Date date = new Date();//相当于new Date(System.currentTimeMillis())
        //操作当前的时间
        System.out.println(date.toString());//Sat Aug 06 19:15:28 CST 2022
        System.out.println(date.toLocaleString());//2022-8-6 19:16:06
        System.out.println(System.currentTimeMillis());//计算从1970年1月1日 0:00:00到目前为止的毫秒数
        System.out.println(date.getYear());//122  =2022-1900
        System.out.println(date.getMonth());//7   0-11   现在是八月
        System.out.println(date.getDate());//6 日
        System.out.println(date.getDay());//6   当前为星期六   注:星期日为0
        System.out.println(date.getHours());//19    当前为19点
        System.out.println(date.getMinutes());//26  当前为26分
        System.out.println(date.getSeconds());//16  当前为16秒
        System.out.println(date.getTime());//1659785176358  计算从1970年1月1日 0:00:00到目前为止的毫秒数
 
        //获取当前的时间 格式为 yyyyMMdd
        java.sql.Date sdate = new java.sql.Date(System.currentTimeMillis());
        System.out.println(sdate.toString());//2022-08-06
 
        java.sql.Date sdate2 = java.sql.Date.valueOf("1896-9-10");
        System.out.println(sdate2.toString());//1896-09-10
 
    }
}
Copy after login

Looking at the API documentation, you can see that many methods in the Date class are obsolete. Date before JDK1.1 included operations such as date operations and converting strings into objects. After JDK1.1, date operation classes generally use the Calendar class, and string conversion uses the DateFormat class.

2.DateFormat class

Format: format

DateFormat is an abstract class, which is generally implemented using its subclass SimpleDateFormat class. The main function is to convert the time object into a string in a specified format. On the contrary, it is to convert the string in the specified format into a time object.

String----->Date

Date----->String

Example:

package li.normalclass.date;
 
import java.text.*;
import java.util.Date;
 
/**
 * 主要操作:
 *   DateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//指定识别的格式
 *
 *   Date date = sdf.parse(strdate);//将字符串转换成日期
 *
 *   String strdate2 = sdf.format(date);//将日期转换成字符串
 */
public class TestDateFormat {
    public static void main(String[] args) throws ParseException {
        String strdate = "1999-12-23 12:12:12";//字符串
 
        //String---->Date
        //DateFormat是抽象类,要实例化只能引用它的子类SimpleDateFormat
        DateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//指定识别的格式
        Date date = sdf.parse(strdate);//将字符串转换成日期
 
        String strdate2 = sdf.format(date);//将日期转换成字符串
        System.out.println(strdate2);
        
    }
}
Copy after login

Common uses of Java date classes

3.Calendar class

Calendar: Calendar

Example:

package li.normalclass.date;
 
import java.util.Calendar;
import java.util.GregorianCalendar;
 
public class TestCalendar {
    public static void main(String[] args) {
        //获取当前的时间
        Calendar cal = new GregorianCalendar();
        // 输出当前的时间
        System.out.println(cal);
        //java.util.GregorianCalendar[time=1659791839017,areFieldsSet=true,areAllFieldsSet=true,lenient=true,zone=sun.util.calendar.ZoneInfo[id="Asia/Shanghai",offset=28800000,dstSavings=0,useDaylight=false,transitions=31,lastRule=null],firstDayOfWeek=1,minimalDaysInFirstWeek=1,ERA=1,YEAR=2022,MONTH=7,WEEK_OF_YEAR=32,WEEK_OF_MONTH=1,DAY_OF_MONTH=6,DAY_OF_YEAR=218,DAY_OF_WEEK=7,DAY_OF_WEEK_IN_MONTH=1,AM_PM=1,HOUR=9,HOUR_OF_DAY=21,MINUTE=17,SECOND=19,MILLISECOND=17,ZONE_OFFSET=28800000,DST_OFFSET=0]
 
        System.out.println(cal.get(Calendar.YEAR));//2022
        System.out.println(cal.get(Calendar.MONTH));//7   0~11  7代表8月
        System.out.println(cal.get(Calendar.DATE));//6   代表6号
        System.out.println(cal.get(Calendar.DAY_OF_WEEK));//7  代表周六  从周日为1开始计算一周
 
        //改变时间
        cal.set(Calendar.DATE,1);//直接指定日期  1号
        cal.set(Calendar.MONTH,1);//直接指定月数  2月
        cal.add(Calendar.DATE,2);//在设置的日期上再加上两天
        System.out.println(cal.get(Calendar.YEAR));//2022 --  22年
        System.out.println(cal.get(Calendar.MONTH));//1 --  2月
        System.out.println(cal.get(Calendar.DATE));//3 --  3号
        System.out.println(cal.get(Calendar.DAY_OF_WEEK));//5 -- 周四
        System.out.println(cal.getActualMaximum(Calendar.DATE));//28 -- 指定月一共有多少天
    }
 
}
Copy after login

The above is the detailed content of Common uses of Java date classes. 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)
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
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.

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.

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.

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