Date类
Date类构造方法为
public Date()
或者
public Date(long date)//将long型转换为Date
public long getTime() 实现Date转换为long型
public static void main(String[] args) {
Date date =new Date();
System.out.println("当前日期为:"+date);
}
结果如图
在这里插入代码片import java.util.Date;
public class Main{
public static void main(String[] args) {
long cur=System.currentTimeMillis();//取得当前日期和时间的long型值
Date date=new Date(cur);//将long型转换为Date
System.out.println(date);
System.out.println(date.getTime());//输出long型
}
}
运行结果
Date得到的日期格式与我们平时所用的并不是很符合,因此可以利用Calendar类和SimpleDateFormat类进行格式化显示
Calendar类
Calendar类是抽象类,必须通过其子类GregorianCalendar实例化操作
在这里插入代码片 package Me;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
public class Main{
public static void main(String[] args) {
long cur=System.currentTimeMillis();//取得当前日期和时间的long型值
Date date=new Date(cur);//将long型转换为Date
System.out.println(date);
System.out.println(date.getTime());//输出long型、
Calendar calendar =null;
calendar=new GregorianCalendar(); //通过Calendar子类实例化
calendar.get(Calendar.YEAR);//取得年
calendar.get(Calendar.MONTH);//月
calendar.get(Calendar.DAY_OF_MONTH);//日
calendar.get(Calendar.HOUR_OF_DAY);//时
calendar.get(Calendar.MINUTE);//分
calendar.get(Calendar.SECOND);//秒
calendar.get(Calendar.MILLISECOND);//毫秒
}
}
**DateFormat类
DateFormat类属于Format类的子类,为一个抽象类,无法直接实例化对象。但是抽象类中提供了静态方法,可以直接取得本类的实例
在这里插入代码片import java.text.DateFormat;
import java.util.Date;
public class Main{
public static void main(String[] args) {
DateFormat df1=null;
DateFormat df2=null;
df1=DateFormat.getDateInstance();//取得日期
df2=DateFormat.getDateTimeInstance();//取得日期时间
System.out.println("Date "+df1.format(new Date()));//格式化日期
System.out.println("DateTime "+df2.format(new Date()));
}
}
运行结果
SimpleDateFormat类:**
可以用于日期格式二点转换
在这里插入代码片 public static void main(String[] args){
String strDate ="2019-05-24 10:10:30.163";
String pat1="yyyy-MM-dd HH:mm:ss.SSS";//准备一个模板,从字符串中提取数字
String pat2="yyyy 年 MM 月 dd 日 HH 时 mm 分 ss 秒 SSS 毫秒";//准备第二个模板,将提取的数字转变为指定的格式
SimpleDateFormat sdf1=new SimpleDateFormat(pat1);//实例化模板对象
SimpleDateFormat sdf2=new SimpleDateFormat(pat2);
Date d =null;
try {
d=sdf1.parse(strDate);//将字符串中的日期提取出来
}catch (ParseException e){
e.printStackTrace();
}
System.out.println(sdf2.format(d));//将日期转化为指定的格式
}
}
运行结果如图所示