


Introduction to methods and usage of using Date and SimpleDateFormat classes to process time in Java
Apr 21, 2023 pm 03:01 PM1. 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歷險(xiǎn)記-@51博客"; public static void main(String args[]){ //產(chǎn)生日期對(duì)象 Date d=new Date(); System.out.println(d); //獲取時(shí)間為長(zhǎng)整型,時(shí)間戳 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; //導(dǎo)入時(shí)間包 import java.util.Date; public class Tested { private final static String name = "磊哥的java歷險(xiǎn)記-@51博客"; public static void main(String args[]){ //創(chuàng)建時(shí)間對(duì)象 Date d2 = new Date(); //年份,Java中的Date表示的是自1900年以來(lái)所經(jīng)過(guò)的時(shí)間 int year = d2.getYear() + 1900; //月份,最后一個(gè)月取決于一年中的月份數(shù)。 因?yàn)檫@個(gè)值的初始值是0,因此我們要用它來(lái)表示正確的月份時(shí)就需要加1。 int month = d2.getMonth() + 1; //日期 int date = d2.getDate(); //小時(shí) 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("小時(shí):" + 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(); //傳入指定時(shí)間格式 SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd"); //日期格式化輸出 System.out.println(sdf.format(d)); } }
Define a tool class:
package Test2; //導(dǎo)入時(shí)間包import java.text.SimpleDateFormat; import java.util.Date; public class MyDate { private final static String name = "磊哥的java歷險(xiǎn)記-@51博客"; // 定義的MyDateDemo類(lèi) private SimpleDateFormat sd = null; // 聲明SimpleDateFormat對(duì)象sd public String getDate01() { // 定義getDate01方法 this.sd = new SimpleDateFormat("yyyy-MM-dd HH:mm;ss.sss"); // 得到一個(gè)"yyyy-MM-dd // HH:mm;ss.sss"格式日期 return this.sd.format(new Date()); // 將當(dāng)前日期進(jìn)行格式化操作 } public String getDate02() { // 定義getDate02方法 this.sd = new SimpleDateFormat("yyyy年MM月dd日 HH時(shí)mm分ss秒sss毫秒"); // 得到一個(gè)"yyyy年MM月dd日 //HH時(shí)mm分ss秒sss毫秒"格式日期 return this.sd.format(new Date()); // 將當(dāng)前日期進(jìn)行格式化操作 } public String getDate03() {// 定義getDate03方法 this.sd = new SimpleDateFormat("yyyyMMddHHmmsssss"); // 得到一個(gè)"yyyyMMddHHmmsssss"格式日期(也就是時(shí)間戳) return this.sd.format(new Date());// 將當(dāng)前日期進(jìn)行格式化操作 } }
Main method call:
package com.Test; import Test2.MyDate; import java.util.Date; public class Main { private final static String name = "磊哥的java歷險(xiǎn)記-@51博客"; public static void main(String[] args) { // 主方法 MyDate dd = new MyDate(); // 聲明dd對(duì)象,并實(shí)例化 System.out.println("默認(rèn)日期格式: " + new Date()); // 分別調(diào)用方法輸入不同格式的日期 System.out.println("英文日期格式: " + dd.getDate01()); System.out.println("中文日期格式: " + dd.getDate02()); System.out.println("時(shí)間戳: " + 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歷險(xiǎn)記-@51博客";
public static void main(String[] args) { // 主方法
//獲取當(dāng)前日期
Date d2=new Date();
//轉(zhuǎn)換為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!

Hot AI Tools

Undress AI Tool
Undress images for free

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

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

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

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

The settings.json file is located in the user-level or workspace-level path and is used to customize VSCode settings. 1. User-level path: Windows is C:\Users\\AppData\Roaming\Code\User\settings.json, macOS is /Users//Library/ApplicationSupport/Code/User/settings.json, Linux is /home//.config/Code/User/settings.json; 2. Workspace-level path: .vscode/settings in the project root directory

To correctly handle JDBC transactions, you must first turn off the automatic commit mode, then perform multiple operations, and finally commit or rollback according to the results; 1. Call conn.setAutoCommit(false) to start the transaction; 2. Execute multiple SQL operations, such as INSERT and UPDATE; 3. Call conn.commit() if all operations are successful, and call conn.rollback() if an exception occurs to ensure data consistency; at the same time, try-with-resources should be used to manage resources, properly handle exceptions and close connections to avoid connection leakage; in addition, it is recommended to use connection pools and set save points to achieve partial rollback, and keep transactions as short as possible to improve performance.

itertools.combinations is used to generate all non-repetitive combinations (order irrelevant) that selects a specified number of elements from the iterable object. Its usage includes: 1. Select 2 element combinations from the list, such as ('A','B'), ('A','C'), etc., to avoid repeated order; 2. Take 3 character combinations of strings, such as "abc" and "abd", which are suitable for subsequence generation; 3. Find the combinations where the sum of two numbers is equal to the target value, such as 1 5=6, simplify the double loop logic; the difference between combinations and arrangement lies in whether the order is important, combinations regard AB and BA as the same, while permutations are regarded as different;

DependencyInjection(DI)isadesignpatternwhereobjectsreceivedependenciesexternally,promotingloosecouplingandeasiertestingthroughconstructor,setter,orfieldinjection.2.SpringFrameworkusesannotationslike@Component,@Service,and@AutowiredwithJava-basedconfi

fixture is a function used to provide preset environment or data for tests. 1. Use the @pytest.fixture decorator to define fixture; 2. Inject fixture in parameter form in the test function; 3. Execute setup before yield, and then teardown; 4. Control scope through scope parameters, such as function, module, etc.; 5. Place the shared fixture in conftest.py to achieve cross-file sharing, thereby improving the maintainability and reusability of tests.

Use classes in the java.time package to replace the old Date and Calendar classes; 2. Get the current date and time through LocalDate, LocalDateTime and LocalTime; 3. Create a specific date and time using the of() method; 4. Use the plus/minus method to immutably increase and decrease the time; 5. Use ZonedDateTime and ZoneId to process the time zone; 6. Format and parse date strings through DateTimeFormatter; 7. Use Instant to be compatible with the old date types when necessary; date processing in modern Java should give priority to using java.timeAPI, which provides clear, immutable and linear

TheJVMenablesJava’s"writeonce,runanywhere"capabilitybyexecutingbytecodethroughfourmaincomponents:1.TheClassLoaderSubsystemloads,links,andinitializes.classfilesusingbootstrap,extension,andapplicationclassloaders,ensuringsecureandlazyclassloa

java.lang.OutOfMemoryError: Javaheapspace indicates insufficient heap memory, and needs to check the processing of large objects, memory leaks and heap settings, and locate and optimize the code through the heap dump analysis tool; 2. Metaspace errors are common in dynamic class generation or hot deployment due to excessive class metadata, and MaxMetaspaceSize should be restricted and class loading should be optimized; 3. Unabletocreatenewnativethread due to exhausting system thread resources, it is necessary to check the number of threads, use thread pools, and adjust the stack size; 4. GCoverheadlimitexceeded means that GC is frequent but has less recycling, and GC logs should be analyzed and optimized.
