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

17,277 Responses

  1. In fact, they should have charities the place they gift Stan Smiths to Congolese children who don’t have shoes (they really should try this).

  2. Realizing that Pil-seong has the money and Jaeseok’s cellphone, Gi-tae calls him and tells him that he’s next to the manhwa shop the place his family works.

  3. ClydePab表示:

    Deneme Bonusu Veren Siteler: Casino Siteleri – casino siteleri win

  4. The Wizards (who had been renamed Sporting Kansas Metropolis) announced on 5 February 2011 that Chhetri had officially left the team.

  5. If you’re excited by traveling to New Zealand to get a style of the region’s wines firsthand, it is perhaps a good suggestion to analyze the Nelson wine path.

  6. A robust Sweet Scent of Incense: A Portrait of Robert Fraser, Brian Clarke, with Harriet Vyner.

  7. okmark your blog and check again here frequently. I’m quite sure I?ll learn lots of new stuff right here! Best of luck for the next!

  8. Trapp then kept three consecutive clean sheets during the UEFA European Below-21 Championship qualification, coming against San Marino U21, Belarus U21 and Bosnia and Herzegovina U21.

  9. Generally, a glass exists in a structurally metastable state with respect to its crystalline form, though in certain circumstances, for example in atactic polymers, there is no crystalline analogue of the amorphous phase.

  10. live sex chat表示:

    Hey there! This is kind of off topic but I need some guidance from an established blog. Is it tough to set up your own blog? I’m not very techincal but I can figure things out pretty quick. I’m thinking about setting up my own but I’m not sure where to start. Do you have any points or suggestions? Thanks

  11. sex cams表示:

    Thanks for your blog post. A few things i would like to add is that computer memory ought to be purchased should your computer is unable to cope with that which you do with it. One can mount two RAM memory boards with 1GB each, for example, but not one of 1GB and one having 2GB. One should make sure the manufacturer’s documentation for the PC to ensure what type of ram it can take.

  12. The next time I learn a blog, I hope that it doesnt disappoint me as a lot as this one. I mean, I know it was my option to read, but I actually thought youd have one thing interesting to say. All I hear is a bunch of whining about one thing that you might repair in the event you werent too busy in search of attention.

  13. I was suggested this website via my cousin. I’m no longer positive whether this submit is written via him as nobody else realize such specified about my difficulty. You are wonderful! Thank you!

  14. cam sex表示:

    Hey just wanted to give you a quick heads up. The words in your article seem to be running off the screen in Chrome. I’m not sure if this is a formatting issue or something to do with web browser compatibility but I thought I’d post to let you know. The design and style look great though! Hope you get the problem solved soon. Thanks

  15. Отличный сайт! Всем рекомендую!шкафы на заказ

  16. In autograph-public sale catalogues the next abbreviations are used to help describe the type of letter or doc that’s being supplied for sale.

  17. Difficulties with these projects made Fairy Tales by Hans Christian Andersen his first printed work, in 1916.

  18. Potential autograph consumers unsure of the legitimacy of the vendor or authenticator could research both parties, and will check any dealer who claims membership of any association.

  19. CarrollUnton表示:

    deneme bonusu veren siteler betturkey http://casinositeleri.win/# Deneme Bonusu Veren Siteler

  20. Just a few other examples for this idea can be seen right here and right here.

  21. The ceremony was to be held on 15 July 1940 and it was planned to rename the ship to OF Paris (OF – Okręt Francuski – “French ship”) however resulting from lack of personnel the ship was by no means handed over to the Polish Navy and was instead utilized by the British as an accommodation ship in Devonport.

  22. These early examples are drawn from Christine Lilyquist (1993).

  23. Quite a couple of, “Look Magazine” is rather more focused.

  24. I’ve been holding my cryptos in Coinbase and incomes interest from other providers like Nexo.

  25. 5.00, good for both days (Noon Friday & eight AM Saturday).

  26. Davis was responsible for the furthest West single-light window in the North wall of the church, the window being entitled “The Nativity”.

  27. Gingerbread hearts are commonly discovered at fall festivals, decorated with coloured icing and tied with ribbons.

  28. She is a cheerful and eccentric 18-12 months-old who lives together with her mother downstairs from him.

  29. The shelving needs to be customized-designed – maybe within the shape of a ship or with parts resembling the iconic Straw Hat Pirates’ flag.

發佈留言

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