Saturday, December 19, 2009

Java Date Format

Below examples explains how to do date format using SimpleDateFormat and how to convert string to date in java.
SimpleDateFormat Example
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
public class DateFormatExample {
    public static void main(String args[]) {
        Date date = new Date();
        String DATE_FORMAT = "MM:dd:yyyy";
        // or
        // String DATE_FORMAT = "MM/dd/yyyy";
        SimpleDateFormat simDateFormat = new SimpleDateFormat(DATE_FORMAT);
        System.out.println("Today is " + simDateFormat.format(date));
        // or If you want display time with AM/PM
        String TIME_FORMAT = "HH:mm:ss a";
        SimpleDateFormat timeFormat = new SimpleDateFormat(TIME_FORMAT);
        System.out.println("Now time is " + timeFormat.format(date));
        // Today date and Time
        System.out.println("Date and time is " + simDateFormat.format(date)
                + " " + timeFormat.format(date));
        }
}
Convert String to Date


import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
public class StrToDate {
    public static void main(String[] args) {
        String stri = "18/12/2009";
        DateFormat simDateForm = new SimpleDateFormat("dd/MM/yyyy");
        Date dstr;
        try {
            dstr = (Date) simDateForm.parse(stri);
            System.out.println("Date is" + dstr);
        } catch (ParseException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
}

0 Comments:

Post a Comment

The Link Exchange - Your ultimate resource for link exchange!

About This Blog

  © Blogger template Webnolia by Ourblogtemplates.com 2009

Back to TOP