Get the current date and time
It is easy to get the current date and time in Java. You can use the ToString () method of a simple date object to print the current date and time as follows:
ImportJava.Util.Date; Public Class Datedemo { Public Static voidMain(string Args[]) { //instantiate a Date object date date = newdate (); //display time and date using toString () system out. Println (date. Tostring }} /span>
This will produce the following results:
Mon may:2009
Format date using SimpleDateFormat:
SimpleDateFormat is a specific class that is used to format and parse dates in a locale-sensitive manner. SimpleDateFormat first selects any user-defined mode for the datetime format. For example:
ImportJava.Util.*;ImportJava.Text.*;Public Class Datedemo { Public Static voidMain(StringArgs[]) { DateDnow= New Date( ); simpledateformat ft = Span class= "KWD" >new simpledateformat ( span class= "str" > "E yyyy. Mm.dd ' at ' hh:mm:ss a zzz "); system.. Println ( "current Date:" + Ft.dnow}} /span>
This will produce the following results:
CurrentDate:Sun2004.07. In:: PM PDT
Format Date with printf:
Date and time formats can be done very easily with the printf method. You can use a two-letter format, ending with one of the letters from T and the table given below. For example:
ImportJava.Util.Date;Public Class Datedemo { Public Static voidMain(StringArgs[]) { Instantiate a Date object DateDate= new date (); //display time and date using toString () String str = string.< Span class= "PLN" >format ( "current Date/time:%TC" , date ); system.. Printfstr}} /span>
This will produce the following results:
CurrentDate/time:SatDec:notoginseng :
Parse String to date:
The SimpleDateFormat class has some additional methods, such as Parse (), which attempts to parse a string based on the format of the object stored in the given SimpleDateFormat. For example:
ImportJava.Util.*;ImportJava.Text.*; Public Class Datedemo { Public Static voidMain(StringArgs[]) { SimpleDateFormatFt= New SimpleDateFormat ("Yyyy-mm-dd"); StringInput=Args.Length== 0 ? "1818-11-11" :Args[0]; System.Out.Print(Input+ "Parses as"); DateT; Try {T=Ft.Parse(Input); Systemout. Printlnt} catch ( Parseexception E) { Span class= "Typ" >system.. Println ( "unparseable using" + Ft); } }} /span>
Running an example of the above program will produce the following results:
$ javaDatedemo1818-11-11 Parses As Wed Nov 11 00:00:00 GMT 1818$ java datedemo 2007-12 -012007- 12-01 parses as satdec 01 00 :00:00 GMT 2007
Java Date Time (date/time)