Date 和 SimpleDateFormat 类表示时间

 1   Date now=new Date();
 2 
 3 // 使用format()方法将日期转换为指定格式的文本
 4 
 5 SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy年MM月dd日 HH时mm分ss秒");
 6 
 7         // 调用format()方法,将日期转换为字符串并输出
 8 
 9 System.out.println( sdf1.format(now)         );
10 
11 // 使用parse()方法将文本转换为日期
12 
13 String d = "2014-6-1 21:05:36";
14 
15 SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");    
16 
17          // 调用parse()方法,将字符串转换为日期
18 
19 Date date =sdf.parse(d);
20 
21        

 

 

 

推荐使用Calendar

java.util.Calendar 类是一个抽象类,可以通过调用 getInstance() 静态方法获取一个 Calendar 对象,此对象已由当前日期时间初始化,即默认代表当前时间,如 Calendar c = Calendar.getInstance();

 1 // 创建Canlendar对象
 2 
 3 Calendar c = Calendar.getInstance();
 4 
 5        
 6 
 7 // 将Calendar对象转换为Date对象
 8 
 9 Date date = c.getTime();
10 
11        
12 
13 // 创建SimpleDateFormat对象,指定目标格式
14 
15 SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
16 
17        
18 
19 // 将日期转换为指定格式的字符串
20 
21 String now = sdf.format(date);
22 
23 System.out.println("当前时间:" + now);
原文地址:https://www.cnblogs.com/rongweijun/p/5440635.html