


Introduction 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+"============="); } }
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+"============="); } }
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)); } }
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+"============="); } }
- (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
- (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
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+"=============");
}
}
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!

Javaremainsagoodlanguageduetoitscontinuousevolutionandrobustecosystem.1)Lambdaexpressionsenhancecodereadabilityandenablefunctionalprogramming.2)Streamsallowforefficientdataprocessing,particularlywithlargedatasets.3)ThemodularsystemintroducedinJava9im

Javaisgreatduetoitsplatformindependence,robustOOPsupport,extensivelibraries,andstrongcommunity.1)PlatformindependenceviaJVMallowscodetorunonvariousplatforms.2)OOPfeatureslikeencapsulation,inheritance,andpolymorphismenablemodularandscalablecode.3)Rich

The five major features of Java are polymorphism, Lambda expressions, StreamsAPI, generics and exception handling. 1. Polymorphism allows objects of different classes to be used as objects of common base classes. 2. Lambda expressions make the code more concise, especially suitable for handling collections and streams. 3.StreamsAPI efficiently processes large data sets and supports declarative operations. 4. Generics provide type safety and reusability, and type errors are caught during compilation. 5. Exception handling helps handle errors elegantly and write reliable software.

Java'stopfeaturessignificantlyenhanceitsperformanceandscalability.1)Object-orientedprincipleslikepolymorphismenableflexibleandscalablecode.2)Garbagecollectionautomatesmemorymanagementbutcancauselatencyissues.3)TheJITcompilerboostsexecutionspeedafteri

The core components of the JVM include ClassLoader, RuntimeDataArea and ExecutionEngine. 1) ClassLoader is responsible for loading, linking and initializing classes and interfaces. 2) RuntimeDataArea contains MethodArea, Heap, Stack, PCRegister and NativeMethodStacks. 3) ExecutionEngine is composed of Interpreter, JITCompiler and GarbageCollector, responsible for the execution and optimization of bytecode.

Java'ssafetyandsecurityarebolsteredby:1)strongtyping,whichpreventstype-relatederrors;2)automaticmemorymanagementviagarbagecollection,reducingmemory-relatedvulnerabilities;3)sandboxing,isolatingcodefromthesystem;and4)robustexceptionhandling,ensuringgr

Javaoffersseveralkeyfeaturesthatenhancecodingskills:1)Object-orientedprogrammingallowsmodelingreal-worldentities,exemplifiedbypolymorphism.2)Exceptionhandlingprovidesrobusterrormanagement.3)Lambdaexpressionssimplifyoperations,improvingcodereadability

TheJVMisacrucialcomponentthatrunsJavacodebytranslatingitintomachine-specificinstructions,impactingperformance,security,andportability.1)TheClassLoaderloads,links,andinitializesclasses.2)TheExecutionEngineexecutesbytecodeintomachineinstructions.3)Memo


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

SublimeText3 English version
Recommended: Win version, supports code prompts!

Safe Exam Browser
Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

SecLists
SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

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

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