JAVA基础 之 日期
程序员文章站
2022-04-07 20:19:28
...
package com.cxy.f; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Date; public class DateAndCalendarTest { public static void main(String[] args) { //Date类对象表示当前日期和时间 //划横线的为过时的方法 就是java不建议再使用的 Date nowDate=new Date(); System.out.println("当前年:"+(nowDate.getYear()+1900)); System.out.println("当前月:"+(nowDate.getMonth()+1)); System.out.println("当前日:"+nowDate.getDate()); System.out.println("当前星期:"+nowDate.getDay()); System.out.println("当前时:"+nowDate.getHours()); System.out.println("当前分:"+nowDate.getMinutes()); System.out.println("当前秒:"+nowDate.getSeconds()); System.out.println("从1970年1月1日起到现在的毫秒:"+nowDate.getTime()); System.out.println("现在的时间是:"+nowDate.toString()); System.out.println("现在的时间是(本地格式):"+nowDate.toLocaleString()); System.out.println("现在的时间是(格林威治时间格式):"+nowDate.toGMTString()); System.out.println("================================"); //常用的时间格式 和 对应方法 //其中yyyy-MM-dd是你要表示的格式 SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); String systemtime=sdf.format(nowDate); System.out.println(systemtime); sdf=new SimpleDateFormat("yyyy-MM-dd hh:mm:ss"); systemtime=sdf.format(nowDate); System.out.println(systemtime); System.out.println("================================"); //时间性能测试,测试代码运行的时间 long startTime=new Date().getTime(); //这里是你自己的方法 long endTime=new Date().getTime(); System.out.println("程序执行用时:"+(endTime-startTime)+"毫秒"); System.out.println("================================"); System.out.println("当前年:"+Calendar.getInstance().get(Calendar.YEAR)); //返回默认地区和时区的Calendar对象 System.out.println("当前月:"+Calendar.getInstance().get(Calendar.MONTH)+1); System.out.println("当前日(月中的):"+Calendar.getInstance().get(Calendar.DAY_OF_MONTH)); System.out.println("当前日(年中的):"+Calendar.getInstance().get(Calendar.DAY_OF_YEAR)); System.out.println("当前星期:"+Calendar.getInstance().get(Calendar.DAY_OF_WEEK)); //周日是第一天 System.out.println("当前时:"+Calendar.getInstance().get(Calendar.HOUR_OF_DAY)); System.out.println("当前分:"+Calendar.getInstance().get(Calendar.MINUTE)); System.out.println("当前秒:"+Calendar.getInstance().get(Calendar.SECOND)); System.out.println("================================"); Calendar muBirthday = Calendar.getInstance(); muBirthday.set(Calendar.YEAR, 1986); muBirthday.set(Calendar.MONTH, 3); muBirthday.set(Calendar.DAY_OF_MONTH,19); System.out.println("我的生日是在一年中的第:"+muBirthday.get(Calendar.DAY_OF_YEAR)+"天"); System.out.println("我的生日是:"+(new Date(muBirthday.getTimeInMillis())).toLocaleString()); System.out.println("================================"); Calendar calObj = Calendar.getInstance(); calObj.add(Calendar.YEAR, 1); System.out.println("1年后:"+calObj.getTime().toLocaleString()); } }