SCJP Certification Questions
Saturday, 24 November 2012
Monday, 19 November 2012
Date Formatting in Java
Date Formatting kinda very trivial. but i found some interesting as well as useful information to convert date objects in java into our own formatting.. There are 3 ways we can format Date object in java using the java.text package.
Here it is the hierarchy structure for java.text package.
Option #1 Using java.text.SimpleDateFormat
SimpleDateFormat is a concrete subclass of DateFormat. It allows you to define your own formatting patterns that are used to display date and time information. It allows formatting (date -> text), parsing (text -> date), and normalization.One of its constructors is shown here:SimpleDateFormat(String formatString)
The argument formatString describes how date and time information is displayed. An example of its use is given here:
SimpleDateFormat sdf = SimpleDateFormat("dd MMM yyyy hh:mm:ss zzz");
In most cases, the number of times a symbol is repeated determines how that data is presented. Text information is displayed in an abbreviated form if the pattern letter is repeated less than four times. Otherwise, the unabbreviated form is used. For example, a zzzz pattern can display Pacific Daylight Time, and a zzz pattern can display PDT. For numbers, the number of times a pattern letter is repeated determines how many digits are presented. For example, hh:mm:ss can present 01:51:15, but h:m:s displays the same time value as 1:51:15.
Finally, M or MM causes the month to be displayed as one or two digits. However, three or more repetitions of M cause the month to be displayed as a text string.
The following program shows how this class is used:
Example #1
// Demonstrate SimpleDateFormat. import java.text.*;
import java.util.*;
public class SimpleDateFormatDemo {
public static void main(String args[]) {
Date date = new Date();
SimpleDateFormat sdf; sdf = new SimpleDateFormat("hh:mm:ss");
System.out.println(sdf.format(date));
sdf = new SimpleDateFormat("dd MMM yyyy hh:mm:ss zzz");
System.out.println(sdf.format(date));
sdf = new SimpleDateFormat("E MMM dd yyyy");
System.out.println(sdf.format(date));
}
}
Sample output from this program is shown here:
11:51:50
19 Feb 1999 11:51:50 CST
Fri Feb 19 1999
19 Feb 1999 11:51:50 CST
Fri Feb 19 1999
Example #2
Parsing a request Date String into Date object, and then format it according to your need:
private SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd");
private SimpleDateFormat sdf2 = new SimpleDateFormat("MM/dd/yy");
//Parses text from a string to produce a
Date.Date checkInDate = sdf2.parse("06/05/2013");
NOTE: The argument of parse method is always be a string.
Option #2 Using java.text.DateFormat
import java.text.DateFormat;
import java.util.Date;
public class DateFormatExample1 {
public static void main(String[] args) {
// Make a new Date object. It will be initialized to the current date.
Date now = new Date();
// See what toString() returns
System.out.println(" 1. " + now.toString());
// Next, try the default DateFormat
System.out.println(" 2. " + DateFormat.getInstance().format(now));
// And the default time and date-time DateFormats
System.out.println(" 3. " + DateFormat.getTimeInstance().format(now));
System.out.println(" 4. " + DateFormat.getDateTimeInstance().format(now));
// Next, try the short, medium and long variants of the default time format
System.out.println(" 5. " + DateFormat.getTimeInstance(DateFormat.SHORT).format(now));
System.out.println(" 6. " + DateFormat.getTimeInstance(DateFormat.MEDIUM).format(now));
System.out.println(" 7. " + DateFormat.getTimeInstance(DateFormat.LONG).format(now));
// For the default date-time format, the length of both the date and time elements can be specified. Here are some examples:
System.out.println(" 8. " + DateFormat.getDateTimeInstance(DateFormat.SHORT, DateFormat.SHORT).format(now));
System.out.println(" 9. " + DateFormat.getDateTimeInstance(DateFormat.MEDIUM, DateFormat.SHORT).format(now));
System.out.println("10. " + DateFormat.getDateTimeInstance(DateFormat.LONG, DateFormat.LONG).format(now));
import java.util.Date;
public class DateFormatExample1 {
public static void main(String[] args) {
// Make a new Date object. It will be initialized to the current date.
Date now = new Date();
// See what toString() returns
System.out.println(" 1. " + now.toString());
// Next, try the default DateFormat
System.out.println(" 2. " + DateFormat.getInstance().format(now));
// And the default time and date-time DateFormats
System.out.println(" 3. " + DateFormat.getTimeInstance().format(now));
System.out.println(" 4. " + DateFormat.getDateTimeInstance().format(now));
// Next, try the short, medium and long variants of the default time format
System.out.println(" 5. " + DateFormat.getTimeInstance(DateFormat.SHORT).format(now));
System.out.println(" 6. " + DateFormat.getTimeInstance(DateFormat.MEDIUM).format(now));
System.out.println(" 7. " + DateFormat.getTimeInstance(DateFormat.LONG).format(now));
// For the default date-time format, the length of both the date and time elements can be specified. Here are some examples:
System.out.println(" 8. " + DateFormat.getDateTimeInstance(DateFormat.SHORT, DateFormat.SHORT).format(now));
System.out.println(" 9. " + DateFormat.getDateTimeInstance(DateFormat.MEDIUM, DateFormat.SHORT).format(now));
System.out.println("10. " + DateFormat.getDateTimeInstance(DateFormat.LONG, DateFormat.LONG).format(now));
}
}
When you run this class, you will see output that looks something like that shown in
1. Tue Nov 04 20:14:11 EST 2003
2. 11/4/03 8:14 PM
3. 8:14:11 PM
4. Nov 4, 2003 8:14:11 PM
5. 8:14 PM
6. 8:14:11 PM
7. 8:14:11 PM EST
8. 11/4/03 8:14 PM
9. Nov 4, 2003 8:14 PM
10. November 4, 2003 8:14:11 PM EST
}
When you run this class, you will see output that looks something like that shown in
1. Tue Nov 04 20:14:11 EST 2003
2. 11/4/03 8:14 PM
3. 8:14:11 PM
4. Nov 4, 2003 8:14:11 PM
5. 8:14 PM
6. 8:14:11 PM
7. 8:14:11 PM EST
8. 11/4/03 8:14 PM
9. Nov 4, 2003 8:14 PM
10. November 4, 2003 8:14:11 PM EST
Option #3 Using java.text.Format
Format formatter;
// The year
formatter = new SimpleDateFormat("yy"); // 02
formatter = new SimpleDateFormat("yyyy"); // 2002
// The month
formatter = new SimpleDateFormat("M"); // 1
formatter = new SimpleDateFormat("MM"); // 01
formatter = new SimpleDateFormat("MMM"); // Jan
formatter = new SimpleDateFormat("MMMM"); // January
// The day
formatter = new SimpleDateFormat("d"); // 9
formatter = new SimpleDateFormat("dd"); // 09
// The day in week
formatter = new SimpleDateFormat("E"); // Wed
formatter = new SimpleDateFormat("EEEE"); // Wednesday
// Get today's date
Date date = new Date();
// Some examples
formatter = new SimpleDateFormat("MM/dd/yy");
String s = formatter.format(date);
// 01/09/02
formatter = new SimpleDateFormat("dd-MMM-yy");
s = formatter.format(date);
// 29-Jan-02
// Examples with date and time; see also
// Formatting the Time Using a Custom Format
formatter = new SimpleDateFormat("yyyy.MM.dd.HH.mm.ss");
s = formatter.format(date);
// 2002.01.29.08.36.33
formatter = new SimpleDateFormat("E, dd MMM yyyy HH:mm:ss Z");
s = formatter.format(date);
// Tue, 09 Jan 2002 22:14:02 -0500
// The year
formatter = new SimpleDateFormat("yy"); // 02
formatter = new SimpleDateFormat("yyyy"); // 2002
// The month
formatter = new SimpleDateFormat("M"); // 1
formatter = new SimpleDateFormat("MM"); // 01
formatter = new SimpleDateFormat("MMM"); // Jan
formatter = new SimpleDateFormat("MMMM"); // January
// The day
formatter = new SimpleDateFormat("d"); // 9
formatter = new SimpleDateFormat("dd"); // 09
// The day in week
formatter = new SimpleDateFormat("E"); // Wed
formatter = new SimpleDateFormat("EEEE"); // Wednesday
// Get today's date
Date date = new Date();
// Some examples
formatter = new SimpleDateFormat("MM/dd/yy");
String s = formatter.format(date);
// 01/09/02
formatter = new SimpleDateFormat("dd-MMM-yy");
s = formatter.format(date);
// 29-Jan-02
// Examples with date and time; see also
// Formatting the Time Using a Custom Format
formatter = new SimpleDateFormat("yyyy.MM.dd.HH.mm.ss");
s = formatter.format(date);
// 2002.01.29.08.36.33
formatter = new SimpleDateFormat("E, dd MMM yyyy HH:mm:ss Z");
s = formatter.format(date);
// Tue, 09 Jan 2002 22:14:02 -0500
Labels:
SimpleDateFormat
Sunday, 18 November 2012
Some potential tripstraps for the SCJP exam.
- ·
Two top-level public classes cannot be in the same source file.
- ·
main() cannot call an instance (non-static) method.
- ·
Methods can have the same name as the constructor(s).
- ·
Watch for thread initiation with classes that don't have a run()
method.
- ·
Local classes cannot access non-final variables.
- ·
Case statements must have values within permissible range.
- ·
Watch for Math class being an option for immutable classes.
- ·
instanceOf is not the same as instanceof.
- ·
Constructors can be private.
- ·
Assignment statements can be mistaken for a comparison; e.g.,
if(a=true)...
- ·
Watch for System.exit() in try-catch-finally blocks.
- ·
Watch for uninitialized variable references with no path of
proper initialization.
- ·
Order of try-catch-finally blocks matters.
- ·
main() can be declared final.
- ·
0.0 == 0.0 is true.
- ·
A class without abstract methods can still be declared abstract.
- ·
RandomAccessFile descends from Object and implements DataInput
and DataOutput.
- ·
Map does not implement Collection.
- ·
Dictionary is a class, not an interface.
- ·
Collection (singular) is an Interface, but Collections (plural)
is a helper class.
- ·
Class declarations can come in any order (e.g., derived first,
base next, etc.).
- ·
Forward references to variables gives a compiler error.
- ·
Multi-dimensional arrays can be "sparse" -- i.e., if
you imagine the array as a matrix, every row need not have the same number of
columns.
- ·
Arrays, whether local or class-level, are always initialized
- ·
Strings are initialized to null, not empty string.
- ·
An empty string is not the same as a null reference.
- ·
A declaration cannot be labelled.
- ·
continue must be in a loop (e.g., for, do, while). It cannot
appear in case constructs.
- ·
Primitive
array types can never be assigned to each other, even though the primitives
themselves can be assigned. For example, ArrayofLongPrimitives =
ArrayofIntegerPrimitives gives compiler error even though longvar = intvar is
perfectly valid.
- ·
A constructor can throw
any exception.
- ·
Initializer blocks are executed in the order of declaration.
- ·
Instance initializers are executed only if an object is
constructed.
- ·
All comparisons involving NaN and a non-NaN always result in
false.
- ·
Default type of a numeric literal with a decimal point is
double.
- ·
int and
long operations / and % can throw an ArithmeticException, while float and
double / and % never will (even in case of division by zero).
- ·
== gives compiler error if the operands are cast-incompatible.
- ·
You can never cast objects of sibling classes (sharing the same
parent).
- ·
equals() returns false if the object types are different. It
does not raise a compiler error.
- ·
No inner class can have a
static member.
- ·
File class has no methods to deal with the contents of the file.
- · InputStream and OutputStream are abstract classes, while DataInput and DataOutput are interfaces.
- import java.util.*;
import statement doesn't import subpackage's(packages inside java.util package) classes, interfaces, Enums & annotations.
It just simply import all these stuff inside the current package(java.util package) - try-catch-finally
whenever a exception occur in the try block it moved to the catch then further if there any exception occur in catch
block it moved to the finally block.. - dot (.) and pipe(|), these special symbols are really very special for java. whenever we use them we need to put double back slash (\\) symbol to escape it.
Subscribe to:
Comments (Atom)
