1. 程式人生 > >JavaLearning:日期操作類

JavaLearning:日期操作類

對象 第一個 add ack println length sys append learning

package org.fun.classdemo;

import java.util.Calendar;
import java.util.GregorianCalendar;

public class DateTime {
	private Calendar calendar = new GregorianCalendar(); // 實例化Calendar對象

	public String getDate() {// 2014-07-30
		StringBuffer buf = new StringBuffer();
		buf.append(calendar.get(Calendar.YEAR)).append("-");
		buf.append(this.addZero((calendar.get(Calendar.MONTH) + 1), 2)).append(
				"-");
		buf.append(this.addZero(calendar.get(Calendar.DAY_OF_MONTH), 2));
		return buf.toString();
	}

	public String getDateTime() {// 2014-07-30 10:19:34.123
		StringBuffer buf = new StringBuffer();
		buf.append(this.getDate()).append(" ");
		buf.append(this.addZero(calendar.get(Calendar.HOUR_OF_DAY), 2)).append(
				":");
		buf.append(this.addZero(calendar.get(Calendar.MINUTE), 2)).append(":");
		buf.append(this.addZero(calendar.get(Calendar.SECOND), 2)).append(".");
		buf.append(this.addZero(calendar.get(Calendar.MILLISECOND), 3));
		return buf.toString();
	}

	public String getDateComplete() {// 2014年07月30日
		StringBuffer buf = new StringBuffer();
		buf.append(calendar.get(Calendar.YEAR)).append("年");
		buf.append(this.addZero((calendar.get(Calendar.MONTH) + 1), 2)).append(
				"月");
		buf.append(this.addZero(calendar.get(Calendar.DAY_OF_MONTH), 2))
				.append("日");
		return buf.toString();
	}

	public String getDateTimeComplete() {// 2014年07月30日10時19分34秒123毫秒
		StringBuffer buf = new StringBuffer();
		buf.append(this.getDateComplete());
		buf.append(this.addZero(calendar.get(Calendar.HOUR_OF_DAY), 2)).append(
				"時");
		buf.append(this.addZero(calendar.get(Calendar.MINUTE), 2)).append("分");
		buf.append(this.addZero(calendar.get(Calendar.SECOND), 2)).append("秒");
		buf.append(this.addZero(calendar.get(Calendar.MILLISECOND), 3)).append(
				"毫秒");
		return buf.toString();
	}

	private String addZero(int temp, int len) {
		StringBuffer str = new StringBuffer();
		str.append(temp);// 增加數字
		while (str.length() < len) {
			str.insert(0, 0); // 在第一個位置加上字母0
		}
		return str.toString();
	}

	public static void main(String args[]) {
		System.out.println(new DateTime().getDate());
		System.out.println(new DateTime().getDateTime());
		System.out.println(new DateTime().getDateComplete());
		System.out.println(new DateTime().getDateTimeComplete());
	}
}

JavaLearning:日期操作類