Java 各種時間上的操作範例

分享一些在專案中用到JAVA與日期相關的操作,包括:

  • 取得目前的年、月、日
  • 判斷兩個日期的大小
  • 計算兩個日期的差距
  • 取得昨天的日期
  • 取得上個月的開始與結束日
package CDIT.stanley;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
import java.util.Calendar;

public class dateOperation {
	
	public static int differentDays(Date date1,Date date2){
        Calendar cal1 = Calendar.getInstance();
        cal1.setTime(date1);
        
        Calendar cal2 = Calendar.getInstance();
        cal2.setTime(date2);
        int day1= cal1.get(Calendar.DAY_OF_YEAR);
        int day2 = cal2.get(Calendar.DAY_OF_YEAR);
        
        int year1 = cal1.get(Calendar.YEAR);
        int year2 = cal2.get(Calendar.YEAR);
        if(year1 != year2){
            int timeDistance = 0 ;
            for(int i = year1 ; i < year2 ; i ++){
                if(i%4==0 && i%100!=0 || i%400==0){
                    timeDistance += 366;
                }
                else{
                    timeDistance += 365;
                }
            }
            return timeDistance + (day2-day1) ;
        }
        else{
            return day2-day1;
        }
    }
	
	public static Date getFirstMonthDay(Calendar calendar) {
		calendar.set(Calendar.DATE, calendar.getActualMinimum(Calendar.DATE));
		return calendar.getTime();
	}

	public static Date getLastMonthDay(Calendar calendar) {
		calendar.set(Calendar.DATE, calendar.getActualMaximum(Calendar.DATE));
		return calendar.getTime();
	}
	
    public static void main(String[] args) throws ParseException {
    	
    	//取得目前的年、月、日
		Calendar calendar = Calendar.getInstance();	
		System.out.println("今天是" + calendar.get(Calendar.YEAR) + "年" + (calendar.get(Calendar.MONTH) + 1) + "月" + calendar.get(Calendar.DAY_OF_MONTH) + "日");
		System.out.println("==================================================");
    	//輸出:今天是2017年8月24日
		
		//判斷兩個日期的大小
    	SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd", Locale.TAIWAN);
    	Date date1 = sdf.parse("2017-08-23");
    	Date date2 = sdf.parse("2016-09-22");
		System.out.println("Date1 < Date2 : " + date1.before(date2));
		System.out.println("Date1 > Date2 : " + date1.after(date2));
		System.out.println("==================================================");
		//輸出:Date1 < Date2 : false、Date1 > Date2 : true
		
		//計算兩個日期的差距
		System.out.println("Date1 & Date2 差距 : " + differentDays(date1 , date2) + "天");
		System.out.println("==================================================");
		//輸出:Date1 & Date2 差距 : 31天
		
		//取得昨天的日期
		calendar = Calendar.getInstance();
		calendar.add(Calendar.DATE, -1);
		String  yestedayDate = sdf.format(calendar.getTime());
		System.out.println("昨天是" + yestedayDate);
		System.out.println("==================================================");
		//輸出:昨天是2017-08-23
		
		//取得上個月的開始與結束日
		calendar = Calendar.getInstance();
		calendar.add(Calendar.MONTH,-1);
		String monthDayFirst = sdf.format(getFirstMonthDay(calendar));
		String monthDayLast = sdf.format(getLastMonthDay(calendar));
		System.out.println("上個月的第一天是" + monthDayFirst);
		System.out.println("上個月的最後一天是" + monthDayLast);
		System.out.println("==================================================");
		//輸出:上個月的第一天是2017-07-01、上個月的最後一天是2017-07-31
    }
}

You may also like...

16,824 Responses

  1. For instance, they’re ready of weakness on the subject of negotiating with supermarket chains that wish to impose costs unilaterally.

  2. Lipka, Michael (12 December 2013).

  3. Fantastic website. Lots of useful information here. I?m sending it to some friends ans also sharing in delicious. And of course, thanks for your sweat!

  4. The success of headmaster Mr Finch has aroused media consideration; investigative journalist Sarah Jane Smith, the Doctor’s former companion, arrives at the varsity and discovers the TARDIS.

  5. mostbetazutSi表示:

    Mostbet-ning rasmiy saytida doimiy aksiyalar va bonuslar | Mostbet-da yangi o‘yinlarni sinab ko‘ring va yutuqlar qo‘lga kiriting | Mostbet orqali yutuqlar va bonuslarni qo‘lga kiriting | Mostbet-da yangi foydalanuvchilar uchun qiziqarli bonuslar | Mostbet-ning bonusli dasturidan foydalaning va qo‘shimcha yutuqlar oling mostbet регистрация

  6. Hi there, I found your web site by way of Google whilst searching for a comparable subject, your web site came up, it looks good. I’ve bookmarked it in my google bookmarks.

  7. Consider or not, a baby doesn’t care if he sleeps in a Dresser drawer, so long as he’s dry and effectively fed.

  8. Melissa Breau: You have got a category on all this arising in August.

  9. Since it’s a blog, after all I additionally write about my personal experiences.

  10. Nothing to report so I went back.

  11. Тут можно преобрести сейфы огнестойкие сейф москва огнестойкий купить

  12. Reminiscence overwrite throughout merc creation fixed (could affect analysis on Mac).

  13. Thus this a part of the home is typically known as the Henry VIII wing, though the King by no means visited.

  14. I looked in on her.

  15. John James Brendan McGahan, Chief Executive, Livestock Advertising Fee.

  16. He argued that inflicting civilian casualties and damaging home infrastructure served each as propaganda and as a means of diverting assets from the entrance line.

  17. How do I select an excellent Irani Firoza gemstone?

  18. promotions表示:

    Thanks a lot for the helpful content. It is also my belief that mesothelioma cancer has an particularly long latency interval, which means that indication of the disease would possibly not emerge till 30 to 50 years after the first exposure to asbestos fiber. Pleural mesothelioma, that’s the most common kind and influences the area throughout the lungs, will cause shortness of breath, breasts pains, as well as a persistent coughing, which may bring on coughing up maintain.

  19. A cushion with vibrant covers is a protected means to usher in some a lot wanted coloration to your modular office furniture.

  20. However keep making excuses to distract from the fact that Michigan has simply been the higher soccer team.

  21. Learn variations on conventional tag that can keep kids having enjoyable for hours with out ever leaving the backyard.

  22. John Michael Barber, Director, Cumbria Deaf Affiliation.

  23. That July, New York Central awarded the overall development contract to James Stewart & Company.

  24. принудительный вывод из запоя ростов [url=www.snatkina.borda.ru/?1-11-0-00000199-000-0-0-1730726180/]www.snatkina.borda.ru/?1-11-0-00000199-000-0-0-1730726180/[/url] .

  25. deal表示:

    What I have usually told people today is that while searching for a good internet electronics retail store, there are a few issues that you have to take into consideration. First and foremost, you would like to make sure to discover a reputable along with reliable retail store that has received great testimonials and scores from other buyers and marketplace professionals. This will make certain you are dealing with a well-known store to provide good program and help to its patrons. Many thanks for sharing your thinking on this website.

  26. вывод из запоя цены на дому ростов [url=http://www.kryto.ukrbb.net/viewtopic.php?f=3&t=1164]http://www.kryto.ukrbb.net/viewtopic.php?f=3&t=1164[/url] .

  27. Office supplies Promo Codes [url=https://skidki-i-kupony.ru]https://skidki-i-kupony.ru[/url] .

  28. Good website! I truly love how it is easy on my eyes and the data are well written. I am wondering how I might be notified when a new post has been made. I have subscribed to your RSS which must do the trick! Have a great day!

發佈留言

發佈留言必須填寫的電子郵件地址不會公開。