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

  1. Ask your stylist to add lengthy layers for lighter, more voluminous kinks.

  2. William Collow, MBE, Chief Officer, Norfolk Hearth Brigade.

  3. The western ramp carries southbound site visitors and the jap ramp carries northbound traffic.

  4. The dreadful decline of morality, the diseases and degeneration of some nations are also the outcomes of the slavish dependence of woman.

  5. Patricia Mary Richards, Support Grade Band 2 (Cleaner), Division of Employment.

  6. William Hunter, JP, Member of Governing Board, North of Scotland College of Agriculture.

  7. From our clothes to the music we hearken to, slightly bit of variety is nice generally.

  8. Esther Stouph, Manageress of Unit Canteen, Chester-le-Street Sea Cadet Corps.

  9. The Convention defines a baby as any human being underneath the age of eighteen, except the state itself defines the age of majority as an earlier age.

  10. Hirst, David, The Gun and the Olive Branch.

  11. That is where electricity will help: and never only in regard to work but in health, hygiene and larger comfort in the house.

  12. Randall Harland Whiteman, Detective Inspector, 1st Glass, New South Wales Police Power.

  13. In March, Sarah took out her lengthy hair extensions – which she wore for her Modern Household character – and as an alternative received what she described as a ‘shagadocious’ quick hairstyle from 9 Zero One salon in Los Angeles, California.

  14. 保険 巧妙表示:

    Strive stringing them alongside the walls of your venue, putting them into a vase or wine bottle for a centerpiece, or even using them to create a faux tent for your exterior festivities.

  15. Rear-Admiral (Basil Charles) Godfrey Place, VC, CB, DSC.

  16. deal表示:

    One other issue issue is that video games are usually serious as the name indicated with the most important focus on studying rather than enjoyment. Although, there is an entertainment factor to keep children engaged, just about every game will likely be designed to work with a specific set of skills or curriculum, such as instructional math or scientific discipline. Thanks for your post.

  17. LloydNoice表示:

    https://kampharm.shop/# cheapest Kamagra Kam Pharm

  18. RobertHam表示:

    http://rybpharm.com/# rybpharm canada

  19. Trefhga表示:

    Сколько стоит диплом высшего и среднего образования и как это происходит?
    maminmir.getbb.ru/viewtopic.php?f=1&t=1769

  20. Hi there just wanted to give you a quick heads up. The text in your content seem to be running off the screen in Internet explorer. 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 style and design look great though! Hope you get the problem resolved soon. Many thanks

  21. deal表示:

    Excellent site. Lots of useful information here. I?m sending it to some friends ans additionally sharing in delicious. And of course, thank you in your effort!

  22. Hey, I think your website might be having browser compatibility issues. When I look at your blog in Firefox, it looks fine but when opening in Internet Explorer, it has some overlapping. I just wanted to give you a quick heads up! Other then that, very good blog!

  23. DennishIp表示:

    best ed pills online: cheapest ed pills ere pharm – ere pharm

  24. JefferyJaf表示:

    1xBet promo code 2025: BOX200VIP bonus up to $130 on sports betting and up to $1,500 and 150 free spins on the casino. First, the registration or welcome bonus is reserved for users who register with the bookmaker. The bonus offered covers deposits made with digital coins, including Ethereum and Bitcoin.

    [url=https://www.amec.com.vn/wp-pages/pag/1xbet-promo-code.html]1xbet promo code today[/url]

  25. Thanks for your write-up. One other thing is the fact that individual American states have their unique laws that affect house owners, which makes it quite difficult for the our elected representatives to come up with the latest set of rules concerning home foreclosure on people. The problem is that a state provides own legal guidelines which may interact in a damaging manner with regards to foreclosure procedures.

  26. Feel free to visit my blog post Daycares By Category

發佈留言

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