java中獲取當前日期和時間的方法

1. 獲取當期日期、年份、月份

  1. import java.util.Calendar;  
  2. public class Main {  
  3.   public static void main(String[] args) {  
  4.     Calendar now = Calendar.getInstance();  
  5.     System.out.println("Current Year is : " + now.get(Calendar.YEAR));  
  6.     // month start from 0 to 11  
  7.     System.out.println("Current Month is : " + (now.get(Calendar.MONTH) + 1));  
  8.     System.out.println("Current Date is : " + now.get(Calendar.DATE));  
  9.   }  
  10. }  
  11.  

 

2. 獲取前一天、前一個月的日期

  1. Calendar calendar = Calendar.getInstance();//此時打印它獲取的是系統當前時間  
  2. calendar.add(Calendar.DATE, -1);    //得到前一天  
  3. String  yestedayDate = new SimpleDateFormat("yyyy-MM-dd").format(cal.getTime());  
  4.         calendar.add(Calendar.MONTH, -1);    //得到前一個月  
  5.         int year = calendar.get(Calendar.YEAR);  
  6.        int month = calendar.get(Calendar.MONTH)+1//輸出前一月的時候要記得加1  
  7.  

 3. 字符串轉爲日期格式

 

  1. String date = "2010-02-01 23:59:59";  
  2. SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");  
  3. try {  
  4. Date d = sf.parse(date);  
  5. System.out.println(sf.format(d));  
  6. catch (ParseException e) {  
  7. e.printStackTrace();  
  8. }  


 

4.完整的一個例子

 

  1. import   java.util.Date;    
  2. import   java.util.Calendar;      
  3. import   java.text.SimpleDateFormat;     
  4. public   class   TestDate{    
  5. public   static   void   main(String[]   args){    
  6. Date   now   =   new   Date();    
  7. SimpleDateFormat   dateFormat   =   new   SimpleDateFormat("yyyy/MM/dd   HH:mm:ss");//可以方便地修改日期格式    
  8. String   hehe   =   dateFormat.format(   now   );    
  9. System.out.println(hehe);      
  10. Calendar   c   =   Calendar.getInstance();//可以對每個時間域單獨修改    
  11. int   year   =   c.get(Calendar.YEAR);    
  12. int   month   =   c.get(Calendar.MONTH);    
  13. int   date   =   c.get(Calendar.DATE);    
  14. int   hour   =   c.get(Calendar.HOUR_OF_DAY);    
  15. int   minute   =   c.get(Calendar.MINUTE);    
  16. int   second   =   c.get(Calendar.SECOND);    
  17. System.out.println(year   +   "/"   +   month   +   "/"   +   date   +   "   "   +hour   +   ":"   +minute   +   ":"   +   second);    
  18. }    
  19. }  

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章