Java时间格式转换输出实现代码示例

在这里插入图片描述

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
 
public class DateUtils {
     
    public static void show() throws ParseException {
        //获取当前日期
        Calendar now = Calendar.getInstance(); 
        int year = now.get(Calendar.YEAR);
        int month = now.get(Calendar.MONTH) + 1;//注意月份
        int day = now.get(Calendar.DAY_OF_MONTH);
        int hour = now.get(Calendar.HOUR_OF_DAY);
        int minute = now.get(Calendar.MINUTE);
        int second = now.get(Calendar.SECOND);
        long millis = now.getTimeInMillis();
        System.out.println(now.getTime()); 
        System.out.println("时间:"+year + month + day + hour + minute + second + millis);
   
        //日期格式化打印
        Date d = new Date(); 
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); 
        String dateNowStr = sdf.format(d); 
        System.out.println("格式化后的日期:" + dateNowStr); 
        
        SimpleDateFormat df=new SimpleDateFormat("yyyy-MM-dd");
        System.out.println("今天的日期:"+df.format(d));   
        System.out.println("两天前的日期:" + df.format(new Date(d.getTime() - 2 * 24 * 60 * 60 * 1000)));  
        System.out.println("三天后的日期:" + df.format(new Date(d.getTime() + 3 * 24 * 60 * 60 * 1000)));
        
        System.out.println("测试:"+sdf.format(new Date(d.getTime() - 2 * 24 * 60 * 60 * 1000)));
         
        //字符串解析为日期
        String str = "2014-9-1 13:08:28"; 
        Date today = sdf.parse(str); 
        System.out.println("字符串转成日期:" + today); 
    }
    public static void main(String[] args) throws ParseException {
    	DateUtils.show();
	}
 
}
posted @ 2022-01-02 13:45  明金同学  阅读(14)  评论(0)    收藏  举报  来源