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

11,322 Responses

  1. One thing is that often one of the most prevalent incentives for making use of your card is a cash-back or rebate supply. Generally, you’ll have access to 1-5 back on various buying. Depending on the credit cards, you may get 1 again on most purchases, and 5 back again on buying made on convenience stores, filling stations, grocery stores and ‘member merchants’.

  2. Lazrxox表示:

    Добрый день!
    Мы готовы предложить дипломы любых профессий по доступным ценам.
    rushkadiplomiks.ru/kupit-diplom-bukhgaltera

  3. Feel free to surf to my blog – highstakespoker

  4. My brother suggested I might like this website. He was entirely right. This post actually made my day. You cann’t imagine just how much time I had spent for this info! Thanks!

  5. certainly like your web site but you need to check the spelling on quite a few of your posts. Several of them are rife with spelling issues and I find it very bothersome to tell the truth nevertheless I?ll certainly come back again.

  6. There are some fascinating points in time on this article but I don?t know if I see all of them heart to heart. There is some validity but I’ll take hold opinion until I look into it further. Good article , thanks and we wish extra! Added to FeedBurner as nicely

  7. Charleshon表示:

    http://indiapharmacy.shop/# best india pharmacy
    cheap ed meds

  8. hiroaki ryota表示:

    Wow, marvelous blog layout! How long have you been blogging for? you make blogging look easy. The overall look of your website is fantastic, as well as the content!

  9. Richardexips表示:

    A chainsaw amnesty is protecting the rainforest in Borneo
    www otzyv ru

    Borneo was once covered in lush, dense rainforests, but they are rapidly disappearing. The Southeast Asian island, roughly three times the size of the UK, has lost half its forest cover since the 1930s, destroying precious habitat for wildlife such as the critically endangered orangutan, as well as valuable carbon stores.

    A non-profit called Health in Harmony (HIH) is asking farmers to hand in their chainsaws in return for money, and a chance to set up an alternative livelihood.

    Borneo is divided between Indonesia, Malaysia and Brunei, and it is estimated that up to 10% of its land is taken up by industrial palm oil and logging operations. But deforestation isn’t just about large-scale tree clearance; some of those behind the logging are small-scale farmers, cutting trees as a sideline to make ends meet.

    Buyback and healthcare
    HIH launched its chainsaw buyback scheme in 2017, under the group’s Indonesian name, Alam Sehat Lestari (ASRI). Farmers who illegally log and sell the wood to timber companies are given around $200 for their chainsaws, as well as up to $450 in financial support for them to set up an alternative, sustainable livelihood, such as opening a shop, organic farming and even beekeeping.

    The scheme also involves addressing the root causes of the problem. According to HIH, many of the farmers who turn to logging do so because they need the money for basics like healthcare.

    “They live far from the healthcare clinics, and they see logging as a place where they can get quick cash,” explained Mahardika “Dika” Putra, conservation program manager at HIH. “If they need this amount of money, they cut this amount of trees.

    “We asked what solutions they think they need to live in harmony with the forest and they said, ‘high quality, affordable healthcare, and training in organic farming.’”

  10. DouglasGed表示:

    reputable indian online pharmacy: indian pharmacy – Online medicine order

  11. DouglasGed表示:

    indian pharmacy paypal: indian pharmacy – Online medicine order

  12. Great site! I recommend it to everyone!Private jet empty legs

  13. DouglasGed表示:

    purple pharmacy mexico price list: Mexico pharmacy online – mexican rx online

  14. I think other site proprietors should take this web site as an model, very clean and great user genial style and design, as well as the content. You are an expert in this topic!

  15. It?s hard to search out knowledgeable individuals on this matter, but you sound like you realize what you?re talking about! Thanks

  16. Iiasei表示:

    cyclosporine uk – methotrexate 10mg without prescription colcrys 0.5mg oral

  17. Hey! I could have sworn I’ve been to this blog before but after reading through some of the post I realized it’s new to me. Nonetheless, I’m definitely glad I found it and I’ll be book-marking and checking back often!

  18. Charleshon表示:

    https://mexicopharmacy.win/# purple pharmacy mexico price list
    get ed prescription online

  19. you’ve got an incredible weblog right here! would you like to make some invite posts on my weblog?

  20. Great write-up, I am normal visitor of one?s web site, maintain up the excellent operate, and It’s going to be a regular visitor for a long time.

  21. I have seen that car insurance firms know the cars and trucks which are at risk from accidents and other risks. They also know what types of cars are given to higher risk as well as higher risk they’ve already the higher the premium amount. Understanding the very simple basics associated with car insurance will help you choose the right style of insurance policy that should take care of your family needs in case you happen to be involved in an accident. Many thanks sharing your ideas in your blog.

  22. Charleshon表示:

    https://edpillpharmacy.store/# ed online prescription
    buy ed pills online

  23. After examine a few of the weblog posts in your website now, and I actually like your approach of blogging. I bookmarked it to my bookmark website checklist and shall be checking back soon. Pls try my website as effectively and let me know what you think.

  24. Great paintings! That is the kind of info that should be shared around the internet. Shame on the seek engines for now not positioning this submit upper! Come on over and seek advice from my site . Thank you =)

  25. This design is steller! You most certainly know how to keep a reader entertained. Between your wit and your videos, I was almost moved to start my own blog (well, almost…HaHa!) Fantastic job. I really enjoyed what you had to say, and more than that, how you presented it. Too cool!

  26. Leonardpar表示:

    http://edpillpharmacy.store/# cost of ed meds

  27. Leonardpar表示:

    https://indiapharmacy.shop/# top 10 pharmacies in india

  28. I do agree with all of the ideas you’ve presented in your post. They’re very convincing and will definitely work. Still, the posts are too short for novices. Could you please extend them a bit from next time? Thanks for the post.

  29. Charleshon表示:

    http://indiapharmacy.shop/# п»їlegitimate online pharmacies india
    online ed treatments

發佈留言

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