java中日期的格式化 时间类

时间:2021-01-06 18:09:51
import java.text.DateFormat;
import java.util.Date;
import java.text.SimpleDateFormat;
class practice6 {
    public static void main(String[] args) 
    {
        //日期的格式化

        //得到一个日期时间格式化对象
        DateFormat df = DateFormat.getDateTimeInstance(DateFormat.SHORT,DateFormat.SHORT);

        //创建需要被格式化的Date对象
        Date  date = new Date();

        //使用DateFormat对象的格式化方法对日期对象进行格式化 
        String time = df.format(date);

        System.out.println(time);

        SimpleDateFormat  sdf = new SimpleDateFormat("yyyy/MM/dd E HH:mm:ss");

        Date d = new Date();

        String shijian = sdf.format(d);

        System.out.println(shijian);
    }
}

当然Date很多已经过时

calendar集中方法

import java.util.Calendar;
class Demo8 
{
    public static void main(String[] args) 
    {
        Calendar cal = Calendar.getInstance();
        //System.out.println(cal);

        String[] months={"1月","2月","3月","4月","5月","6月","7月","8月","9月","10月","11月","12月"};
        String[] weeks = {"","星期日","星期1","星期2","星期3","星期4","星期5","星期6"};

        int nian = cal.get(Calendar.YEAR);
        int yue = cal.get(Calendar.MONTH);
        String month = months[yue];


        int riqi = cal.get(Calendar.DAY_OF_MONTH);
        int xingqi = cal.get(Calendar.DAY_OF_WEEK);
        String week = weeks[xingqi];


        System.out.println(nian+"年"+month+riqi+"日"+week);
    }
}