Halaman

Subscribe:

Main Menu

Jumat, Mei 09, 2008

DateFormat dalam java

Terkadang kita juga butuh untuk memproses tanggal. sesuai dengan tampilan keinginan kita. dalam java kita bisa memanfaatkan Class java.text.DateFormat dan lain2. berikut ini adalah contoh penggunaannya :

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 time.
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));
}
}
Hasil
> java DateFormatExample1
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

Terkadang juga kita butuh mendapatkan nilai tanggal dari input data String. nah kita bisa manfaatin class tadi juga. caranya kayak gini nech

import java.text.DateFormat;
import java.text.ParseException;
import java.util.Date;

public class DateFormatExample2 {

public static void main(String[] args) {
// Make a String that has a date in it, with MEDIUM date format
// and SHORT time format.
String dateString = "Nov 4, 2003 8:14 PM";

// Get the default MEDIUM/SHORT DateFormat
DateFormat format =
DateFormat.getDateTimeInstance(
DateFormat.MEDIUM, DateFormat.SHORT);

// Parse the date
try {
Date date = format.parse(dateString);
System.out.println("Original string: " + dateString);
System.out.println("Parsed date : " +
date.toString());
}
catch(ParseException pe) {
System.out.println("ERROR: could not parse date in string \"" +
dateString + "\"");
}
}
}
Hasil
> java DateFormatExample2
Original string: Nov 4, 2003 8:14 PM
Parsed date : Tue Nov 04 20:14:00 EST 2003

0 komentar: