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

15,487 Responses

  1. Scottdiz表示:

    pin up casino: pin up casino – pin up casino

  2. Scottdiz表示:

    1хбет официальный сайт: 1xbet официальный сайт – 1xbet зеркало

  3. Warrenmof表示:

    http://vavada.auction/# vavada casino

  4. Scottdiz表示:

    vavada зеркало: вавада казино – vavada зеркало

  5. Lhaneevige表示:

    Excellent, what a website it is! This web site gives useful information to us, keep it up.
    вавада online

  6. Scottdiz表示:

    пин ап казино: пин ап казино – пин ап вход

  7. Scottdiz表示:

    vavada казино: казино вавада – вавада казино

  8. Warrenmof表示:

    http://1xbet.contact/# 1хбет зеркало

  9. Warrenmof表示:

    http://pin-up.diy/# пин ап вход

  10. Scottdiz表示:

    pin up casino: пинап казино – пин ап зеркало

  11. One thing is that when you’re searching for a education loan you may find that you will need a co-signer. There are many cases where this is correct because you will find that you do not possess a past credit rating so the financial institution will require that you’ve someone cosign the financial loan for you. Good post.

  12. We’re a bunch of volunteers and starting a new scheme in our community. Your site offered us with helpful information to work on. You’ve done a formidable process and our entire community can be thankful to you.

  13. Another issue is really that video gaming became one of the all-time greatest forms of entertainment for people of every age group. Kids have fun with video games, plus adults do, too. The actual XBox 360 has become the favorite gaming systems for those who love to have a lot of activities available to them, and also who like to play live with some others all over the world. Thank you for sharing your notions.

  14. Also visit my web page: Find top-rated certified Daycares in your
    area (incometaxusa.net)

  15. The heart of your writing whilst appearing agreeable in the beginning, did not really work well with me personally after some time. Someplace throughout the paragraphs you were able to make me a believer but only for a while. I however have a problem with your leaps in assumptions and you would do well to fill in all those gaps. If you can accomplish that, I will undoubtedly be fascinated.

  16. Once I originally commented I clicked the -Notify me when new comments are added- checkbox and now every time a comment is added I get 4 emails with the same comment. Is there any way you’ll be able to take away me from that service? Thanks!

  17. I have observed that car insurance companies know the motors which are prone to accidents and also other risks. Additionally, these people know what form of cars are prone to higher risk plus the higher risk they’ve already the higher the actual premium fee. Understanding the very simple basics involving car insurance can help you choose the right types of insurance policy which will take care of your preferences in case you get involved in an accident. Thank you for sharing the actual ideas on your blog.

  18. Thanks for the new things you have discovered in your short article. One thing I would like to comment on is that FSBO connections are built after some time. By releasing yourself to owners the first end of the week their FSBO is actually announced, prior to masses start off calling on Thursday, you develop a good interconnection. By mailing them equipment, educational resources, free accounts, and forms, you become a good ally. By using a personal fascination with them along with their circumstances, you create a solid link that, on many occasions, pays off in the event the owners opt with a representative they know in addition to trust – preferably you.

  19. Warrenmof表示:

    https://1xbet.contact/# 1xbet зеркало рабочее на сегодня

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

  21. Scottdiz表示:

    пин ап вход: pin up – пин ап вход

  22. StephenDeery表示:

    Pretty part of content. I just stumbled upon your website and in accession capital to say that I acquire actually enjoyed account your blog posts. Anyway I will be subscribing to your feeds or even I fulfillment you get admission to constantly fast.
    https://chicagoreader.com/food-drink/jennifer-kims-pojangmacha-and-more-food-and-drink-to-look-forward-to-in-the-fall/

  23. okmark your weblog and check again here frequently. I’m quite certain I will learn lots of new stuff right here! Best of luck for the next!

  24. Scottdiz表示:

    1win: 1win официальный сайт – 1вин зеркало

  25. Hello! Do you know if they make any plugins to safeguard against hackers? I’m kinda paranoid about losing everything I’ve worked hard on. Any tips?

  26. Hello! Someone in my Myspace group shared this site with us so I came to take a look. I’m definitely loving the information. I’m bookmarking and will be tweeting this to my followers! Wonderful blog and excellent design and style.

  27. Thank you for any other wonderful post. The place else could anybody get that type of info in such a perfect means of writing? I’ve a presentation next week, and I’m on the look for such info.

  28. Lazrarr表示:

    Здравствуйте!
    Мы готовы предложить дипломы любой профессии по разумным ценам.
    coub.com/aaurusdiploms

發佈留言

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