Search This Blog

Tuesday, April 6, 2010

How to formate date into user defined patterns?

SimpleDateFormat allows you to start by choosing any user-defined patterns for date-time formatting. All that you need to do is provide the date format string along with the constructor. You can find the format letters in SimpleDateFormat javadocs. For example we have given few formats below:

Date and Time PatternResult
"yyyy.MM.dd G 'at' HH:mm:ss z"

2001.07.04 AD at 12:08:56 PDT
"EEE, MMM d, ''yy"Wed, Jul 4, '01
"h:mm a"12:08 PM

"hh 'o''clock' a, zzzz"12 o'clock PM, Pacific Daylight Time
"K:mm a, z"0:08 PM, PDT

The sample code also given below for your reference.

Sample Code:

import java.text.SimpleDateFormat;
import java.util.Date;

public class DateFormatter {
    public static void main(String a[]){
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy.MM.dd G 'at' HH:mm:ss z");
        System.out.println("yyyy.MM.dd G 'at' HH:mm:ss z  ---> "+sdf.format(new Date()));
        sdf = new SimpleDateFormat("hh 'o''clock' a, zzzz");
        System.out.println("hh 'o''clock' a, zzzz  ---> "+sdf.format(new Date()));


yyyy.MM.dd G 'at' HH:mm:ss z  ---> 2010.04.06 AD at 19:30:50 IST
hh 'o''clock' a, zzzz  ---> 07 o'clock PM, India Standard Time

Monday, April 5, 2010

How to get different country currency formats in java?

Java provides NumberFormat class to support currency formats based on local. All you need to do is get currency instance for NumberFormat class and calling format() method on top of the instance. An example is given below for your reference.

Sample Code:

import java.text.NumberFormat;
import java.util.Locale;

public class Currency {

    public static void main(String a[]){
        NumberFormat nf = NumberFormat.getCurrencyInstance(Locale.US);
        double currency = 52.12;
        System.out.println("In Dollars: "+nf.format(currency));
        nf = NumberFormat.getCurrencyInstance(Locale.UK);
        System.out.println("In British Pound: "+nf.format(currency));


In Dollars: $52.12
In British Pound: £52.12