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

27,476 Responses

  1. Richardprurf表示:

    https://tadalafilmeilleurprix.com/# pharmacie en ligne livraison europe
    pharmacie en ligne

  2. WilsonVah表示:

    trouver un mГ©dicament en pharmacie: pharmacie en ligne – pharmacie en ligne

  3. Jacobbep表示:

    pharmacie en ligne france fiable http://tadalafilmeilleurprix.com/# pharmacie en ligne

  4. ok365表示:

    Fantastic website. Lots of helpful info here. I am sending it to some pals ans also sharing in delicious. And obviously, thanks for your sweat!

  5. NorbertKep表示:

    Viagra gГ©nГ©rique sans ordonnance en pharmacie: viagra en ligne – Viagra gГ©nГ©rique sans ordonnance en pharmacie

  6. ok365表示:

    Right now it appears like Expression Engine is the best blogging platform available right now. (from what I’ve read) Is that what you’re using on your blog?

  7. Perryzoozy表示:

    vente de mГ©dicament en ligne pharmacie en ligne france fiable pharmacie en ligne pas cher

  8. ok365表示:

    Thanks , I’ve just been searching for information approximately this subject for a while and yours is the greatest I’ve discovered till now. However, what in regards to the conclusion? Are you positive concerning the supply?

  9. ok365表示:

    Hey! This is my first visit to your blog! We are a group of volunteers and starting a new initiative in a community in the same niche. Your blog provided us valuable information to work on. You have done a extraordinary job!

  10. ok365表示:

    I?d have to check with you here. Which isn’t one thing I often do! I get pleasure from reading a publish that will make folks think. Additionally, thanks for allowing me to comment!

  11. WilsonVah表示:

    pharmacie en ligne france pas cher: Tadalafil sans ordonnance en ligne – pharmacie en ligne

  12. Perryzoozy表示:

    pharmacie en ligne avec ordonnance Pharmacies en ligne certifiees trouver un mГ©dicament en pharmacie

  13. One important thing is that when you find yourself searching for a education loan you may find that you’ll want a co-signer. There are many cases where this is true because you will find that you do not employ a past credit standing so the financial institution will require you have someone cosign the loan for you. Good post.

  14. NorbertKep表示:

    pharmacie en ligne france livraison internationale: kamagra oral jelly – Pharmacie en ligne livraison Europe

  15. nsfw ai chat表示:

    Very informative blog article. Will read on…

  16. Jacobbep表示:

    pharmacie en ligne france livraison internationale http://viagrameilleurprix.com/# Viagra homme prix en pharmacie sans ordonnance

  17. Jacobbep表示:

    pharmacie en ligne france fiable https://viagrameilleurprix.com/# Viagra homme prix en pharmacie sans ordonnance

  18. I have learned new things from your blog post. One other thing to I have recognized is that in many instances, FSBO sellers can reject a person. Remember, they would prefer to never use your companies. But if you maintain a stable, professional romance, offering aid and keeping contact for around four to five weeks, you will usually have the ability to win a conversation. From there, a house listing follows. Many thanks

  19. Thanks for your posting. One other thing is that if you are selling your property on your own, one of the challenges you need to be alert to upfront is when to deal with household inspection reports. As a FSBO supplier, the key about successfully transferring your property along with saving money on real estate agent income is understanding. The more you recognize, the simpler your property sales effort will likely be. One area in which this is particularly important is home inspections.

  20. WilsonVah表示:

    vente de mГ©dicament en ligne: achat kamagra – Pharmacie sans ordonnance

  21. WilsonVah表示:

    pharmacie en ligne: pharmacie en ligne – pharmacie en ligne france livraison belgique

  22. Perryzoozy表示:

    Pharmacie sans ordonnance achat kamagra pharmacie en ligne avec ordonnance

  23. Richardprurf表示:

    http://pharmaciemeilleurprix.com/# acheter mГ©dicament en ligne sans ordonnance
    pharmacie en ligne france livraison belgique

  24. obviously like your web-site however you have to test the spelling on quite a few of your posts. Several of them are rife with spelling issues and I in finding it very troublesome to inform the truth then again I?ll certainly come again again.

  25. You made some respectable points there. I looked on the web for the issue and located most people will go along with with your website.

  26. Many thanks for your post. I want to say that the cost of car insurance varies greatly from one scheme to another, due to the fact there are so many different facets which give rise to the overall cost. For example, the make and model of the car or truck will have a massive bearing on the price. A reliable aged family motor vehicle will have a less expensive premium than a flashy expensive car.

  27. NorbertKep表示:

    Viagra homme sans ordonnance belgique: viagra en ligne – Viagra pas cher paris

發佈留言

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