Pure Java – 62 Dates, Numbers & Currency – DateFormat & SimpleDateFormat

Merhaba Arkadaslar,
Bu yazimda java.text.DateFormat  ve java.text.SimpleDateFormat  siniflarindan bahsedecegim.

DateFormat
java.text.DateFormat sinifi da java.util.Calendar sinifi gibi abstract bir siniftir. Benzer sekilde getInstance() veya overloaded getDateInstance() metodundan birisi kullanilir. getInstance() metodu da getDateTimeInstance() metodunu cagirmaktadir.

    public final static DateFormat getInstance() {
        return getDateTimeInstance(SHORT, SHORT);
    }
....
    public final static DateFormat getDateTimeInstance(int dateStyle,
                                                       int timeStyle)
    {
        return get(timeStyle, dateStyle, 3, Locale.getDefault(Locale.Category.FORMAT));
    }

getDateInstance() metodu da getDateTieInstance(..) metodu da get metodunu cagirmaktadir. get metodunu inceledigimiz de geriye SimpleDateFormat tipinde obje dondurdugunu gorebiliriz. SimpleDateFormat IS-A DateFormat tir.

    private static DateFormat get(int timeStyle, int dateStyle,
                                  int flags, Locale loc) {
        if ((flags & 1) != 0) {
            if (timeStyle < 0 || timeStyle > 3) {
                throw new IllegalArgumentException("Illegal time style " + timeStyle);
            }
        } else {
            timeStyle = -1;
        }
        if ((flags & 2) != 0) {
            if (dateStyle < 0 || dateStyle > 3) {
                throw new IllegalArgumentException("Illegal date style " + dateStyle);
            }
        } else {
            dateStyle = -1;
        }
        try {
            // Check whether a provider can provide an implementation that's closer
            // to the requested locale than what the Java runtime itself can provide.
            LocaleServiceProviderPool pool =
                LocaleServiceProviderPool.getPool(DateFormatProvider.class);
            if (pool.hasProviders()) {
                DateFormat providersInstance = pool.getLocalizedObject(
                                                    DateFormatGetter.INSTANCE,
                                                    loc,
                                                    timeStyle,
                                                    dateStyle,
                                                    flags);
                if (providersInstance != null) {
                    return providersInstance;
                }
            }

            return new SimpleDateFormat(timeStyle, dateStyle, loc);
        } catch (MissingResourceException e) {
            return new SimpleDateFormat("M/d/yy h:mm a");
        }
    }

Ihtiyaca gore ilgili metotlardan getInstance() ya da getDateInstance() in overloaded metotlarindan birisi kullanilabilir. Aralarindaki fark format ile ilgilidir.

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

public class DateFormatTest {
	public static void main(String[] args) {
		Date date = new Date();

		System.out.println("Date :" + date);

		DateFormat dateFormat = DateFormat.getInstance();
		System.out.println("getInstance() : " + dateFormat.format(date));

		dateFormat = DateFormat.getDateInstance();
		System.out.println("getDateInstance() : " + dateFormat.format(date));

		dateFormat = DateFormat.getDateInstance(DateFormat.SHORT);
		System.out.println("getDateInstance(DateFormat.SHORT):" + dateFormat.format(date));

		dateFormat = DateFormat.getDateInstance(DateFormat.MEDIUM);
		System.out.println("getDateInstance(DateFormat.MEDIUM):" + dateFormat.format(date));

		dateFormat = DateFormat.getDateInstance(DateFormat.LONG);
		System.out.println("getDateInstance(DateFormat.LONG):" + dateFormat.format(date));

		dateFormat = DateFormat.getDateInstance(DateFormat.FULL);
		System.out.println("getDateInstance(DateFormat.LONG):" + dateFormat.format(date));
	}
}

DateFormat sinifinda format metodu yer almaktadir bu metot Date degeri uygun formatta String ‘ e cevirmektedir.

    public final String format(Date date)
    {
        return format(date, new StringBuffer(),
                      DontCareFieldPosition.INSTANCE).toString();
    }

DateFormat sinifinda parse metodu yer almaktadir bu metot String degeri uygun sekilde Date e cevirmektedir. Bu metot ParseException hatasi firlatabilir bu exception bir checked exceptiondir.

    public Date parse(String source) throws ParseException
    {
        ParsePosition pos = new ParsePosition(0);
        Date result = parse(source, pos);
        if (pos.index == 0)
            throw new ParseException("Unparseable date: \"" + source + "\"" ,
                pos.errorIndex);
        return result;
    }

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

public class DateFormatTest2 {

	public static void main(String[] args) throws ParseException {
		Date date = new Date();

		DateFormat dateFormat = DateFormat.getInstance();

		System.out.println(date);

		// System.out.println(dateFormat.parse(date)));
		// parse metodu String deger alir Date e cevirir.

		String toStringDate = date.toString();
		String formattedDate = dateFormat.format(date);

		// System.out.println(dateFormat.parse(toStringDate)); //
		// java.text.ParseException: Unparseable date hatasi verir. Ilgili
		// String in formati
		// bu format icin parse etmeye uygun degil.

		System.out.println(dateFormat.parse(formattedDate));

		dateFormat = DateFormat.getDateInstance(DateFormat.SHORT);
		formattedDate = dateFormat.format(date);

		System.out.println(formattedDate);
		System.out.println(dateFormat.parse(formattedDate));

		// parse metodu DateFormat a gore saniye kismini ya da saat dakika
		// saniye kismini 00
		// olarak parse eder.
		// ihtiyaca gore kullanilabilir.

		/*
		 * Fri Oct 31 21:51:36 EET 2014
		 * Fri Oct 31 21:51:00 EET 2014
		 * 10/31/14
		 * Fri Oct 31 00:00:00 EET 2014
		 */
	}
}

SimpleDateFormat
Ozellesmis bir date/tarih formati icin SimpleDateFormat sinifini kullanabiliriz. SimpleDateFormat linkinden yararlanip ilgili harflerin anlamini anlayabiliriz. Diledigimiz formata uygun sekilde duzenleme yapabiliriz.

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

public class SimpleDateFormatTest {

	public static void main(String[] args) {
		Date date = new Date();

		SimpleDateFormat sdf = new SimpleDateFormat();
		System.out.println(sdf.format(date));

		sdf = new SimpleDateFormat("MM-dd-yy");
		System.out.println(sdf.format(date));

		sdf = new SimpleDateFormat("MM/dd/yyyy");
		System.out.println(sdf.format(date));

		sdf = new SimpleDateFormat("MM/dd/yyyy HH:mm");
		System.out.println(sdf.format(date));

		sdf = new SimpleDateFormat("MM/dd/yyyy E  HH:mm");
		System.out.println(sdf.format(date));

		sdf = new SimpleDateFormat("MM/dd/yyyy E  HH:mm:ss:SS a ");
		System.out.println(sdf.format(date));
		
		sdf = new SimpleDateFormat("MM/dd/yyyy E  HH:mm:ss:SS a ");
		System.out.println(sdf.format(date));

		sdf = new SimpleDateFormat("dd.MM.yy E  hh:mm:ss:SS a ");
		System.out.println(sdf.format(date));
		
		sdf = new SimpleDateFormat("dd.MMM.yy ");
		System.out.println(sdf.format(date));
		// http://docs.oracle.com/javase/6/docs/api/java/text/SimpleDateFormat.html

	}
}

Java DateFormat ve SimpleDateFormat siniflariyla tarih/date formati icin esnek yapiya sahiptir. Diledigimiz sekilde kullanabiliriz.

Yazimi burada sonlandiriyorum.
Herkese Bol Javali Gunler dilerim.
Be an oracle man , import java.*;
Levent Erguder
OCP, Java SE 6 Programmer
OCE, Java EE 6 Web Component Developer

Print Friendly, PDF & Email

Leave a Reply

Your email address will not be published. Required fields are marked *