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...

15,982 Responses

  1. instagram viewer tagged photos [url=www.anstoriesview.com/]www.anstoriesview.com/[/url] .

  2. Damon表示:

    Visit my web site … Daycare Near Me (Damon)

  3. Профессиональный сервисный центр по ремонту объективов в Москве.
    Мы предлагаем: объектив ремонт
    Наши мастера оперативно устранят неисправности вашего устройства в сервисе или с выездом на дом!

  4. Профессиональный сервисный центр по ремонту серверов в Москве.
    Мы предлагаем: вызвать мастера по ремонту сетевых хранилищ
    Наши мастера оперативно устранят неисправности вашего устройства в сервисе или с выездом на дом!

  5. Профессиональный сервисный центр по ремонту плоттеров в Москве.
    Мы предлагаем: ремонт плоттера в москве
    Наши мастера оперативно устранят неисправности вашего устройства в сервисе или с выездом на дом!

  6. HeathZex表示:

    pharmacie en ligne sans ordonnance: Pharmacie en ligne livraison Europe – pharmacie en ligne fiable

  7. HeathZex表示:

    pharmacie en ligne pas cher: Acheter Cialis 20 mg pas cher – pharmacie en ligne pas cher

  8. Stephengen表示:

    http://pharmaciepascher.pro/# pharmacies en ligne certifiГ©es

  9. HeathZex表示:

    pharmacie en ligne france livraison internationale: Cialis generique prix – vente de mГ©dicament en ligne

  10. Charlesrab表示:

    Viagra 100mg prix viagra sans ordonnance Viagra homme prix en pharmacie

  11. whoah this blog is excellent i like studying your articles. Keep up the great paintings! You recognize, lots of individuals are hunting around for this information, you can help them greatly.

  12. Charlesrab表示:

    Viagra homme sans prescription Meilleur Viagra sans ordonnance 24h Viagra pas cher livraison rapide france

  13. Профессиональный сервисный центр по ремонту бытовой техники с выездом на дом.
    Мы предлагаем:сервисные центры по ремонту техники в уфе
    Наши мастера оперативно устранят неисправности вашего устройства в сервисе или с выездом на дом!

  14. Nice blog here! Also your website loads up very fast! What web host are you using? Can I get your affiliate link to your host? I wish my web site loaded up as fast as yours lol

  15. Stephengen表示:

    http://vgrsansordonnance.com/# Viagra pas cher livraison rapide france

  16. Профессиональный сервисный центр по ремонту объективов в Москве.
    Мы предлагаем: ремонт объектива
    Наши мастера оперативно устранят неисправности вашего устройства в сервисе или с выездом на дом!

  17. It’s appropriate time to make a few plans for the future and it is time to be happy. I have learn this post and if I may I want to suggest you some attention-grabbing issues or tips. Maybe you can write next articles regarding this article. I want to read more issues about it!

  18. HeathZex表示:

    vente de mГ©dicament en ligne: cialis sans ordonnance – pharmacies en ligne certifiГ©es

  19. HeathZex表示:

    pharmacies en ligne certifiГ©es: pharmacie en ligne sans ordonnance – vente de mГ©dicament en ligne

  20. HeathZex表示:

    vente de mГ©dicament en ligne: pharmacie en ligne sans ordonnance – pharmacies en ligne certifiГ©es

  21. 千葉 金融表示:

    While some people and companies have achieved important success and generated substantial income through POD, others might experience more modest results.

  22. 福岡 寿司表示:

    Find out the latest entry steerage, what documents you’ll want to visit, high issues to see and do, and extra!

  23. One stretch along the route of the bullet train gave us our greatest view of Mt Fuji but, whereas the final train to Takayama gave us probably the most picturesque views but – of snow capped mountains, of dashing blue rivers and of small isolated villages.

  24. This is a great sport to play after telling the story of Captain Kidd.

  25. More than 99 of murders in the U.S.

  26. Shiftin’ our gaze, we spotted the bull out within the north pasture eagerly courtin’ one of many cows.

  27. They are ideal for cooler seasons and colder climates, providing consolation in chilly weather.

  28. Hi there just wanted to give you a quick heads up and let you know a few of the pictures aren’t loading properly. I’m not sure why but I think its a linking issue. I’ve tried it in two different browsers and both show the same outcome.

發佈留言

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