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

  1. Thank you for this article. I’d also like to express that it can often be hard when you are in school and starting out to establish a long credit history. There are many students who are just simply trying to endure and have long or good credit history can occasionally be a difficult thing to have.

  2. I have realized some considerations through your blog post. One other subject I would like to say is that there are numerous games out there designed mainly for toddler age small children. They incorporate pattern recognition, colors, wildlife, and styles. These generally focus on familiarization as an alternative to memorization. This helps to keep children and kids engaged without experiencing like they are studying. Thanks

  3. Cucina usata表示:

    It?s laborious to find educated individuals on this subject, but you sound like you know what you?re talking about! Thanks

  4. Purchasing one’s first home can be a daunting task.

  5. 寝れ ぬ表示:

    The varsity was managed by the Cary College Committee under the management of C. W. Scott, chair.

  6. Even this was not sufficient for new York Life, which in 1924 introduced plans to build a skyscraper uptown at 51 Madison Avenue, on the site of Madison Sq.

  7. Dnrtvfa表示:

    Привет!
    Заказать документ о получении высшего образования можно в нашей компании в столице.
    nemoskvichi.ru/forum/viewtopic.php?f=42&t=145893

  8. A trader may have to work out stop loss limits, lot sizes and what kind of order to place.

  9. IWMS helps an organization to the use of available resources including the management of a company’s infrastructure portfolio, and facilities assets.

  10. I simply couldn’t go away your web site prior to suggesting that I really loved the usual information an individual provide on your visitors? Is gonna be back continuously in order to investigate cross-check new posts

  11. AnthonyPress表示:

    buying from online mexican pharmacy mexican drugstore online mexican mail order pharmacies

  12. The operations of Mutual Funds are regularly monitored by SEBI.

  13. In 2000, which of these was introduced as a stripped-down racing version of a previous model?

  14. There’s noticeably a bundle to learn about this. I assume you made sure nice factors in options also.

  15. One thing I’d like to touch upon is that weightloss system fast may be possible by the proper diet and exercise. People’s size not only affects appearance, but also the entire quality of life. Self-esteem, major depression, health risks, as well as physical skills are disturbed in putting on weight. It is possible to make everything right but still gain. Should this happen, a problem may be the offender. While a lot of food instead of enough physical exercise are usually accountable, common medical ailments and popular prescriptions might greatly enhance size. Thx for your post in this article.

  16. I’ve been browsing online greater than three hours today, but I by no means discovered any interesting article like yours. It is beautiful value sufficient for me. Personally, if all web owners and bloggers made just right content as you probably did, the internet will likely be much more helpful than ever before.

  17. Cucina usata表示:

    I’m truly enjoying the design and layout of your site. It’s a very easy on the eyes which makes it much more pleasant for me to come here and visit more often. Did you hire out a designer to create your theme? Exceptional work!

  18. you are really a good webmaster. The website loading speed is incredible. It seems that you’re doing any unique trick. Moreover, The contents are masterwork. you’ve done a fantastic job on this topic!

  19. Robertengep表示:

    http://easyrxcanada.com/# canadian mail order pharmacy

  20. Cucina usata表示:

    Thank you, I have recently been looking for information approximately this topic for a long time and yours is the best I’ve discovered till now. However, what concerning the bottom line? Are you positive concerning the source?

  21. Hi, i think that i noticed you visited my weblog so i got here to ?go back the want?.I’m attempting to in finding things to improve my site!I suppose its ok to make use of a few of your ideas!!

  22. JeremyPsymn表示:

    http://easyrxindia.com/# cheapest online pharmacy india

  23. I do enjoy the way you have framed this specific challenge and it does indeed supply us some fodder for consideration. Nevertheless, from everything that I have personally seen, I only trust as other reviews pack on that people today stay on issue and in no way get started upon a tirade associated with the news du jour. All the same, thank you for this superb piece and even though I can not necessarily concur with it in totality, I value the perspective.

  24. JeremyPsymn表示:

    https://mexstarpharma.com/# mexican pharmaceuticals online

  25. Definitely believe that which you stated. Your favourite reason appeared to be on the web the easiest thing to understand of. I say to you, I certainly get irked even as folks consider issues that they plainly do not understand about. You controlled to hit the nail upon the highest as neatly as outlined out the whole thing without having side-effects , other people can take a signal. Will probably be back to get more. Thanks

  26. A person essentially help to make seriously articles I would state. This is the very first time I frequented your website page and thus far? I amazed with the research you made to create this particular publish amazing. Great job!

  27. One more thing. I really believe that there are lots of travel insurance internet sites of respectable companies that allow you to enter a trip details and get you the quotes. You can also purchase the international holiday insurance policy online by using your current credit card. Everything you should do is always to enter your own travel details and you can view the plans side-by-side. Merely find the program that suits your allowance and needs and after that use your bank credit card to buy the idea. Travel insurance online is a good way to begin looking for a reputable company with regard to international travel insurance. Thanks for giving your ideas.

  28. I have observed that of all varieties of insurance, health insurance coverage is the most marked by controversy because of the issue between the insurance cover company’s necessity to remain profitable and the consumer’s need to have insurance cover. Insurance companies’ commission rates on health and fitness plans have become low, hence some firms struggle to make a profit. Thanks for the ideas you talk about through this blog.

發佈留言

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