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

38,313 Responses

  1. DavidCooth表示:

    http://garuda888.top/# Banyak pemain berusaha untuk mendapatkan jackpot

  2. DavidCooth表示:

    http://garuda888.top/# Kasino sering memberikan hadiah untuk pemain setia

  3. Curve Finance表示:

    Hi my loved one! I want to say that this article is amazing, great written and come with almost all important infos. I?d like to look extra posts like this .

  4. ThomasThype表示:

    Pemain harus menetapkan batas saat bermain: slotdemo – slot demo pg gratis

  5. Williecrady表示:

    Pemain harus memahami aturan masing-masing mesin http://preman69.tech/# Banyak kasino memiliki program loyalitas untuk pemain

  6. click here表示:

    Greetings! I know this is kinda off topic but I was wondering which blog platform are you using for this site? I’m getting sick and tired of WordPress because I’ve had problems with hackers and I’m looking at options for another platform. I would be awesome if you could point me in the direction of a good platform.

  7. ThomasThype表示:

    Keseruan bermain slot selalu menggoda para pemain: slot88 – slot 88

  8. ThomasThype表示:

    Kasino di Bali menarik banyak pengunjung: bonaslot – bonaslot

  9. Curve Finance表示:

    Thanks for your suggestions. One thing I’ve noticed is that banks and also financial institutions have in mind the spending patterns of consumers and as well understand that most of the people max out their cards around the trips. They properly take advantage of this particular fact and commence flooding your own inbox along with snail-mail box together with hundreds of 0 APR credit cards offers soon after the holiday season comes to an end. Knowing that in case you are like 98 of all American general public, you’ll get at the one opportunity to consolidate card debt and transfer balances to 0 interest rates credit cards.

  10. DavidCooth表示:

    https://preman69.tech/# Banyak pemain mencari mesin dengan RTP tinggi

  11. DavidCooth表示:

    https://preman69.tech/# Kasino memastikan keamanan para pemain dengan baik

  12. Josephzoorp表示:

    Thieves blow up museum door and steal ancient artifacts, including 2,500-year-old gold helmet
    жесток порно видео

    Thieves have stolen four ancient artifacts, including an approximately 2,500-year-old gold helmet, after using explosives to break into a museum in the Netherlands.

    The daring heist took place at Drents Museum in Assen during the early hours of Saturday morning, according to Dutch police, who said they received a report of an explosion at 3:45 a.m. local time.

    CCTV footage released by police shows the suspects opening an exterior door before a blast sends sparks and smoke into the air. The thieves made off with three gold bracelets, dating from around 50 BC, as well as the 5th-century BC Helmet of Cotofenesti, a historically important artifact on loan from the National History Museum of Romania in Bucharest.
    The items were part of an exhibition about the Dacians, an ancient society that occupied much of present-day Romania before being conquered by the Romans. On show since July, “Dacia: Empire of Gold and Silver” featured treasures borrowed from institutions across Romania.

    In a press release on its website, Drents Museum described the Helmet of Cotofenesti — which was discovered in a Romanian village almost a century ago — as a “masterpiece.” Its design features mythological scenes and a pair of eyes, located above the wearers’, that were thought to deter enemies during battle while protecting against the “evil eye.”
    The exhibition was set to conclude Sunday, though Drents Museum remained closed through the weekend due to the robbery. Its premises were damaged by the explosion, though no injuries were reported, the museum said.

    Dutch police announced that they are working with global police agency Interpol and had, as of Sunday, received more than 50 tip-offs. Investigators are currently looking for information about a gray car that was stolen from the nearby city of Alkmaar earlier in the week and was discovered around four miles from the crime scene, on fire, shortly after the overnight heist.

  13. Williecrady表示:

    Jackpot besar bisa mengubah hidup seseorang https://garuda888.top/# Permainan slot bisa dimainkan dengan berbagai taruhan

  14. Williecrady表示:

    Slot menawarkan kesenangan yang mudah diakses http://bonaslot.site/# Banyak pemain menikmati bermain slot secara online

  15. Williecrady表示:

    Slot dengan fitur interaktif semakin banyak tersedia http://slotdemo.auction/# Slot dengan grafis 3D sangat mengesankan

  16. Fox Website表示:

    A formidable share, I simply given this onto a colleague who was doing just a little evaluation on this. And he in fact bought me breakfast as a result of I found it for him.. smile. So let me reword that: Thnx for the treat! However yeah Thnkx for spending the time to discuss this, I feel strongly about it and love reading more on this topic. If attainable, as you change into experience, would you mind updating your weblog with extra particulars? It is highly useful for me. Large thumb up for this blog submit!

  17. ThomasThype表示:

    Banyak pemain menikmati jackpot harian di slot: slot88 – slot88.company

  18. DavidCooth表示:

    https://slotdemo.auction/# Slot klasik tetap menjadi favorit banyak orang

  19. Aaronbus表示:

    preman69.tech preman69.tech Slot dengan pembayaran tinggi selalu diminati

  20. DavidCooth表示:

    http://slot88.company/# Mesin slot dapat dimainkan dalam berbagai bahasa

  21. Williecrady表示:

    Beberapa kasino memiliki area khusus untuk slot https://bonaslot.site/# п»їKasino di Indonesia sangat populer di kalangan wisatawan

  22. author表示:

    There are some attention-grabbing cut-off dates in this article however I don?t know if I see all of them heart to heart. There is some validity but I will take maintain opinion till I look into it further. Good article , thanks and we want extra! Added to FeedBurner as well

  23. Aaronbus表示:

    bonaslot.site bonaslot Pemain sering berbagi tips untuk menang

  24. ThomasThype表示:

    п»їKasino di Indonesia sangat populer di kalangan wisatawan: slot88.company – slot88

  25. ThomasThype表示:

    Permainan slot mudah dipahami dan menyenangkan: slot demo – slot demo

  26. author表示:

    fantastic issues altogether, you just won a new reader. What could you suggest about your publish that you made some days ago? Any sure?

  27. ThomasThype表示:

    Permainan slot mudah dipahami dan menyenangkan: bonaslot.site – bonaslot

  28. DavidCooth表示:

    http://preman69.tech/# Mesin slot dapat dimainkan dalam berbagai bahasa

  29. DavidCooth表示:

    https://slot88.company/# Permainan slot mudah dipahami dan menyenangkan

發佈回覆給「DavidCooth」的留言 取消回覆

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