Date related classes
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 } }
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); } }
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 -- 指定月一共有多少天 } }
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!

JavaachievesplatformindependencethroughtheJavaVirtualMachine(JVM),allowingcodetorunondifferentoperatingsystemswithoutmodification.TheJVMcompilesJavacodeintoplatform-independentbytecode,whichittheninterpretsandexecutesonthespecificOS,abstractingawayOS

Javaispowerfulduetoitsplatformindependence,object-orientednature,richstandardlibrary,performancecapabilities,andstrongsecurityfeatures.1)PlatformindependenceallowsapplicationstorunonanydevicesupportingJava.2)Object-orientedprogrammingpromotesmodulara

The top Java functions include: 1) object-oriented programming, supporting polymorphism, improving code flexibility and maintainability; 2) exception handling mechanism, improving code robustness through try-catch-finally blocks; 3) garbage collection, simplifying memory management; 4) generics, enhancing type safety; 5) ambda expressions and functional programming to make the code more concise and expressive; 6) rich standard libraries, providing optimized data structures and algorithms.

JavaisnotentirelyplatformindependentduetoJVMvariationsandnativecodeintegration,butitlargelyupholdsitsWORApromise.1)JavacompilestobytecoderunbytheJVM,allowingcross-platformexecution.2)However,eachplatformrequiresaspecificJVM,anddifferencesinJVMimpleme

TheJavaVirtualMachine(JVM)isanabstractcomputingmachinecrucialforJavaexecutionasitrunsJavabytecode,enablingthe"writeonce,runanywhere"capability.TheJVM'skeycomponentsinclude:1)ClassLoader,whichloads,links,andinitializesclasses;2)RuntimeDataAr

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.


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 Mac version
God-level code editing software (SublimeText3)

Dreamweaver CS6
Visual web development tools

WebStorm Mac version
Useful JavaScript development tools

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

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