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,783 Responses

  1. 万科 株価表示:

    The unifying characteristic of these uninformed leftist lemmings is that they have a pathological dependence for statism and its false promise of nanny-state security.

  2. I really like these footwear dearly – each my associate and I’ve a pair of our personal and we never go anywhere with out packing them with us!

  3. さる 足跡表示:

    “Chicken wings and fries.” Preston discovered his fried rooster method from his mom, Loraine, who everybody called “Lo” (he goes by “Rell,” which is the place the identify for his cart got here from).

  4. Obtainable in loads f color selections to suit your type and choice.

  5. Shakespeare Stamps, Stratford-upon-Avon, U.K.

  6. The 327 makes an amazing journey shoe if you’re on your ft all day and the retro model looks great with a range of outfits.

  7. In the course of the covid-19 pandemic, it’s extra essential than ever to get journey insurance and verify it provides adequate cover.

  8. Even after walking by means of mud, we were able to clean the boots simply to get them trying new.

  9. Brad does not present drawn plans, written notes or reports, or implementation services.

  10. Meliora’s menu adjustments incessantly, however usually features conventional Italian pasta shapes (sacchetti, the “little sacks,” or mandilli di seta, the evocatively named “silk handkerchiefs”) with non-traditional flavors, together with every little thing from pickled onion to coconut to sumac-spiced lamb neck.

  11. The third and last step-by-step instruction teaches you to draw spiral horns which are widespread for the antelopes.

  12. And I think all too many scientists assume that everyone is aware of what they know, and particularly members of Congress, and members of the administration.

  13. みさいる表示:

    If you have already got sprites drawn in your recreation, choose the same lighting path.

  14. They are perfect for cooler seasons and colder climates, providing consolation in chilly weather.

  15. So you need to choose a that comes with a excessive-high quality GPU.

  16. 4 of them built bombs when they were in high school.

  17. With the costs of living going up at an alarming fee, procuring wholesale can prevent substantial quantities of cash.

  18. As I point out in part two, diversity is important.

  19. Use curved traces to attach the eyes and chin of the goat head.

  20. This time, the membership was able to complete constructing a new constructing in less than a year.

  21. Сервисный центр предлагает срочный ремонт посудомоечных машин gorenje ремонт посудомоечных машин gorenje на дому

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

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

  24. HeathZex表示:

    Pharmacie sans ordonnance: Cialis sans ordonnance 24h – Pharmacie sans ordonnance

  25. Stephengen表示:

    https://vgrsansordonnance.com/# Viagra pas cher inde

  26. HeathZex表示:

    Pharmacie Internationale en ligne: pharmacie en ligne fiable – pharmacie en ligne fiable

  27. HeathZex表示:

    pharmacie en ligne sans ordonnance: Cialis generique prix – trouver un mГ©dicament en pharmacie

  28. Stephenideox表示:

    Работал в Центре судебной экспертизы (в прошлом Казахской научно-исследовательский институт судебных экспертиз) с 1977 года, имею почетные грамоты за заслуги от Министра юстиции СССР и Республики Казахстан.

    Мой многолетний стаж работы ( 45 лет) с судебными делами любой инстанции по вышеуказанному направлениям позволяет выдать вам экспертное заключение, отвечающие требованиям объективности, всесторонности и полноты исследований.

  29. Charlesrab表示:

    Viagra sans ordonnance livraison 48h Sildenafil Viagra Viagra vente libre pays

發佈留言

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