Springboot study notes 2-date conversion

1. Date format

java.util.Date日期格式为:年月日时分秒 
java.sql.Date日期格式为:年月日
java.sql.Time日期格式为:时分秒 
java.sql.Timestamp日期格式为:年月日时分秒毫秒(微秒、纳秒)

 

2. Date format

//获取当前时间
//Date类型日期格式:Fri Apr 08 21:18:35 CST 2020
Date now = new Date();

//获取11天前的Date格式时间
Date startDate = DateUtils.addDays(now, -11);

3. Timestamp format

//获取当前时间,毫秒级
Timestamp d = new Timestamp(System.currentTimeMillis()); 

4. Date format and Timestamp format conversion

Convert Date format to Timestamp format:

//获取当前Date格式时间
Date now = new Date();

//Date格式转换为long
long tsLong = now.getTime();

//转换为Timestamp格式时间,毫秒级:yyyy-MM-dd HH:mm:ss.SSS
try {  
    Timestamp ts = new Timestamp(tsLong); 
} catch (Exception e) {  
    e.printStackTrace();  
}  

Convert Timestamp format to Date format:

//获取当前Timestamp 格式时间
Timestamp d = new Timestamp(System.currentTimeMillis()); 

//Timestamp 格式转换为long
long tsLong = now.getTime();

//转换为Date格式时间
try {  
    Date date = new Date (tsLong);
} catch (Exception e) {  
    e.printStackTrace();  
}  

5. Date format and String format conversion

//将Date格式时间转换为String:yyyy-MM-dd HH:mm:ss
Date now = new Date();
SimpleDateFormat sdf= new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", java.util.Locale.CHINA);
try {  
    String str = sdf.format(startDate);
} catch (Exception e) {  
    e.printStackTrace();  
}  

//将String格式转换为Date格式
SimpleDateFormat sdf=new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
String str="2018/07/12 10:11:12";
try {  
    Date date=sdf.parse(str);
} catch (Exception e) {  
    e.printStackTrace();  
}  

6, Timestamp format and String format conversion

SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")
Timestamp now = new Timestamp(System.currentTimeMillis())
try {  
    String str = df.format(now)
} catch (Exception e) {  
    e.printStackTrace();  
}  

//将String格式转换为Date格式
Timestamp ts = new Timestamp(System.currentTimeMillis());  
String tsStr = "2011-05-09 11:49:45";  
try {  
    ts = Timestamp.valueOf(tsStr);  
} catch (Exception e) {  
    e.printStackTrace();  
}  
//注:String的类型必须形如: yyyy-mm-dd hh:mm:ss[.f...] 这样的格式,中括号表示可选,否则报错!!!

Guess you like

Origin blog.csdn.net/wishxiaozhu/article/details/106054365