Date类和SimpleDateFormat
1.Date类:表示特定的瞬间,精确到毫秒
所属的包:import java.util.Date;
构造方法:
Date();//根据当前时间创建的日期对象
Date(long date);//从1970-01-01 00:00:00开始计算的时间,毫秒
long date = 1000(毫秒)60(分钟)60(小时),即1小时,因为是东八区,最后给出的是9点。用long类型是因为int类型会出现溢出。
long time = (long)100060602430,即一个月
Date d = new Date(time);//1970-01-31 08:00:00
2.Date对象<–>毫秒值
从Date对象得到一个毫秒值:public long getTime();//获取的是毫秒值,从1970-01-01 00:00:00开始
从一个毫秒值得到一个Date对象:方法一:public void setTime(long time);//设置时间,给的是毫秒值 方法二:构造方法Date(long time);
3.SimpleDateFormat
所属的包:java.text.SimpleDateFormat
功能:格式化和解析日期的具体类
格式化日期–>文本,Date–>String: public final String format(Date date);
解析文本–>日期,String–>Date: public Date parse(String source);//可能会有java.text.ParseException
代码:
//Date–>String
Date d = new Date();
SimpleDateFormat sdf = new SimpleDateFormat(“yyyy年MM月dd日 HH:mm:ss”);
String s = sdf.format(d);
System.out.println(s);//2019年07月10日 15:37:59
可以自己定义pattern,比如:
HH:mm:ss
yyyy-MM-dd HH:mm:ss EEE(EEE表示星期几)
因为Date对象在创立时,已经给每个字符设置了属性
//String–>Date 把一个字符串解析为日期的时候,要注意模式字符串和给定的日期字符串的格式要匹配
String str = “2080-08-08 12:23:45”;
SimpleDateFormat sdf = new SimpleDateFormat(“yyyy-MM-dd HH:mm:ss”);
Date d = sdf.parse(str);//throws ParseException
System.out.println(d);//Thu Aug 08 12:23:45 CST 2080
4.写Date工具类DateUtil
把日期转换为指定格式的字符串
把指定格式的字符串解析为日期
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
public class DateUtil{
private DateUtil(){}
public static String dateToString(Date date, String pattern){
SimpleDateFormat sdf = new SimpleDateFormat(pattern);
String s = sdf.format(date);
return s;
}
public static Date StringToDate(String data, String pattern) throws ParseException{
SimpleDateFormat sdf = new SimpleDateFormat(pattern);
Date d = sdf.parse(data);
return d;
}
}
5.Calendar日历类
所在包:java.util.Calendar
Calendar cal = Calendar.getInstance();//创建Calendar的对象,表示的是当前时间
int year = cal.get(Calendar.YEAR);
int month = cal.get(Calendar.MONTH) + 1;//第一个月是0,第二个月是1
int day = cal.get(Calendar.DAY_OF_MONTH);
int week = cal.get(Calendar.DAY_OF_WEEK) - 1;//星期日是1,星期一是2
cal.set(Calendar.YEAR, 2018);//设置年
int year2 = cal.get(Calendar.YEAR);//获取年
//Calendar的转换功能
Date date = new Date(1000);
cal.setTime(date);//可以把date表示的时间设置给cal, Date–>Calendar
Date time = cal.getTime();//用cal的获取时间的方法可以获取到date对象,Calendar–>Date
对象也可以比较大小
如果想比较两个对象的大小,可以通过实现Comparable接口,重写compareTo方法。
接口,比较器:java.lang.Comparable
方法:public int compareTo(T o);
调用方法:int i = stu1.compareTo(stu2);//this:stu1; o:stu2
如果大于,用1表示;
如果小于,用-1表示;
如果相等,用0表示。
类声明:
public class Student implements Comparable{
@Override
public int compareTo(Student o){
if(this.getAge() > o.getAge()){return 1;}//大于
else if(this.getAge() < o.getAge()){return -1;}//小于
else{return 0;}//相等
}
}