首页 > 基础教程 > 常用类 > 常用 Date类
Java Date类
在JDK1.0中,Date类是唯一的一个代表时间的类,但是由于Date类不便于实现国际化,所以从JDK1.1版本开始,推荐使用Calendar类进行时间和日期处理。
构造函数
//使用系统当前时间创建日期对象
Date()
//使用年,月,日创建日期对象
Date(int year, int month, int date)
常用方法
void setTime(long date) //通过时间戳设置时间
String toString() //格式化时间
例子
1. 返回当前时间,包括年月日时分秒
/**
* 获取现在时间
* @return 返回短时间字符串格式yyyy-MM-dd HH:mm:ss
*/
public static String DateDemo1() {
Date currentTime = new Date();
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String dateString = formatter.format(currentTime);
return dateString;
}
2. 获取传入日期所在月的首日
public static Date DateDemo2(Date date) {
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
calendar.set(Calendar.DATE, 1);
return DateUtil.setMinTime(calendar).getTime();
}
3. 设置时间前推或后推分钟
public static Date DateDemo3(String sj1, String jj) {
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date d;
try {
d = format.parse(sj1);
long Time = (d.getTime() / 1000) + Integer.parseInt(jj) * 60;
d.setTime(Time * 1000);
} catch (Exception e) {}
return d;
}
版权声明:本文为JAVASCHOOL原创文章,未经本站允许不得转载。