import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
//日期功能类
public class DateFunction {
//获取当前日期
public static Date getCurrentDate(){
Date date=new Date();
return date;
}
//返回当前年月日格式日期 yyyy-mm-dd
public static String getCurrentShortDate() {
DateFormat df1=null;
Date date=new Date();
df1=DateFormat.getDateInstance();//通过类提供的静态方法直接产生子类实例
return df1.format(date);
}
//取得当前日期和时间 格式yyyy-mm-dd hh:mi:ss
public static String getCurrentDateTime(){
DateFormat df1=null;
Date date=new Date();
df1=DateFormat.getDateTimeInstance();
return df1.format(date);
}
//返回"yyyy年xx月xx日"格式的日期
public static String getCurrentChineseDate(){
DateFormat df1=null;
Date date=new Date();
df1=DateFormat.getDateInstance(DateFormat.FULL,new Locale("zh","CN"));//按照中国人习惯输出日期格式
return df1.format(date);
}
//将字符串日期转换为日期类型,字符串格式 yyyy-mm-dd,如果转换失败,抛出异常
public static Date convertDate(String currentDate){
Date d=null;
SimpleDateFormat sdf1=new SimpleDateFormat("yyyy-MM-dd");
try{
d=sdf1.parse(currentDate);//把日期字符串中的日期部分抽取出来生成一个Date对象
}catch(Exception e){
}
return d;
}
//将日期时间:yyyy-mm-dd hh:mi:ss转换为日期类型,如果转换失败,抛出转换异常
public static Date convertToLongDate(String currentDate){
Date d=null;
SimpleDateFormat sdf1=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
try{
d=sdf1.parse(currentDate);//把日期字符串中的日期部分抽取出来生成一个Date对象
}catch(Exception e){
}
return d;
}
//将日期类型转换为字符串类型 格式yyy-mm-dd
public static String convertToDateString(Date date){
SimpleDateFormat sdf1=new SimpleDateFormat("yyyy-mm-dd");
String str=sdf1.format(date);//把日期按指定的模板格式格式化输出为字符串
return str;
}
//将日期类型转换为字符串类型 格式yyy-mm-dd
public static String convertToDateTimeString(Date date){
SimpleDateFormat sdf1=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String str=sdf1.format(date);//把日期按指定的模板格式格式化输出为字符串
return str;
}
}
public class DateFunctionTest {
public static void main(String[] args){
System.out.println(DateFunction.getCurrentDate());//Wed Jul 27 12:09:10 CST 2016
System.out.println(DateFunction.getCurrentShortDate());//2016-7-27
System.out.println(DateFunction.getCurrentDateTime());//2016-7-27 12:14:15
System.out.println(DateFunction.getCurrentChineseDate());//2016年7月27日 星期三
System.out.println(DateFunction.convertDate("2016-7-27"));//Wed Jul 27 00:00:00 CST 2016
System.out.println(DateFunction.convertToLongDate("2010-10-19 10:11:30.345"));//Tue Oct 19 10:11:30 CST 2010
System.out.println(DateFunction.convertToDateString(DateFunction.convertDate("2016-7-27")));//2016-00-27
System.out.println(DateFunction.convertToDateTimeString(DateFunction.convertToLongDate("2010-10-19 10:11:30.345")));//2010-10-19 10:11:30
}
}
日期功能类DateFunction
最新推荐文章于 2022-02-22 20:20:00 发布