java时间格式的拼凑和格式化

不用多说,对于某一些特殊的地方,需要用到特殊的时间格式,如最常见的2014-01-20 23:00:44’589,直接上源代码:

拼凑


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

public class GetDateDemo {
    public static String getDate(){

        StringBuffer buf = new StringBuffer();

        Calendar calendar = new GregorianCalendar();

        buf = buf.append(calendar.get(Calendar.YEAR)).append("-")
                .append(AddZero((calendar.get(Calendar.MONTH)+1),2)).append("-")
                .append(AddZero(calendar.get(Calendar.DAY_OF_MONTH),2)).append(" ")
                .append(AddZero(calendar.get(Calendar.HOUR_OF_DAY),2)).append(":")
                .append(AddZero(calendar.get(Calendar.MINUTE),2)).append(":")
                .append(AddZero(calendar.get(Calendar.SECOND),2)).append("'")
                .append(AddZero(calendar.get(Calendar.MILLISECOND),3));
        return buf.toString();

    }

    private static String AddZero(int num,int len) {
        StringBuffer buf = new StringBuffer();
        buf.append(num);
        while(buf.length()<;len){ buf.insert(0,"0"); } return buf.tostring(); public static void main(string[] args){ system.out.println(getdatedemo.getdate()); 获取当前时间 < pre>

格式化

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
public class DateChangeDemo {
    public static void main(String[] args) throws ParseException {
        String arg = "2008-08-08 08:08:08.088";
        Date date = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SS").parse(arg);
        System.out.println(date);
        String s = new SimpleDateFormat("yyyy年MM月dd日 HH时mm分ss秒SS毫秒").format(date);
        System.out.println(s);
    }
}
0%