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

38,386 Responses

  1. Victorprima表示:

    The pharmacists always take the time to answer my questions.
    buying cheap clomid pill
    Their multilingual support team is a blessing.

  2. WalterCherm表示:

    A beacon of reliability and trust.
    https://gabapentinpharm24.top/
    Their worldwide outreach programs are commendable.

  3. Flirt表示:

    very good post, i definitely love this web site, keep on it

  4. Victorprima表示:

    The team always keeps patient safety at the forefront.
    order clomid without a prescription
    Their free health check-ups are a wonderful initiative.

  5. Jasonzitte表示:

    Making global healthcare accessible and affordable.
    where can i get generic cytotec without dr prescription
    Leading the charge in international pharmacy standards.

  6. Jasonzitte表示:

    Trusted by patients from all corners of the world.
    gabapentin overdose uptodate
    Appreciate their commitment to maintaining global healthcare standards.

  7. michaelphelps表示:

    El entrenamiento de Michael Phelps es un modelo para los atletas | Michael Phelps ha sido un símbolo de disciplina y constancia | Michael Phelps ha sido reconocido por su impacto en el deporte Michael Phelps natación.

  8. What an eye-opening and thoroughly-researched article! The author’s attention to detail and ability to present complex ideas in a comprehensible manner is truly praiseworthy. I’m extremely enthralled by the scope of knowledge showcased in this piece. Thank you, author, for offering your knowledge with us. This article has been a real game-changer!

  9. Thanks for your post. One other thing is that if you are selling your property alone, one of the concerns you need to be conscious of upfront is how to deal with property inspection reports. As a FSBO vendor, the key concerning successfully switching your property as well as saving money about real estate agent commissions is information. The more you already know, the softer your home sales effort is going to be. One area exactly where this is particularly crucial is home inspections.

  10. WalterCherm表示:

    Been a loyal customer for years and they’ve never let me down.
    https://cipropharm24.top/
    Their global presence never compromises on quality.

  11. Thanks for your publication on the travel industry. I will also like to add that if your senior contemplating traveling, it is absolutely crucial to buy travel insurance for seniors. When traveling, golden-agers are at high risk being in need of a healthcare emergency. Obtaining right insurance cover package in your age group can safeguard your health and provide peace of mind.

  12. Heterosexual表示:

    I’m not sure exactly why but this weblog is loading extremely slow for me. Is anyone else having this problem or is it a issue on my end? I’ll check back later on and see if the problem still exists.

  13. Great beat ! I would like to apprentice at the same time as you amend your site, how can i subscribe for a weblog web site? The account helped me a appropriate deal. I were tiny bit acquainted of this your broadcast provided vibrant clear concept

  14. Lionel Kleman表示:

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

  15. amorous表示:

    I do believe that a foreclosed can have a major effect on the client’s life. Property foreclosures can have a Several to a decade negative influence on a client’s credit report. A new borrower that has applied for home financing or virtually any loans for instance, knows that the worse credit rating is, the more difficult it is to obtain a decent bank loan. In addition, it could possibly affect the borrower’s ability to find a good place to lease or rent, if that results in being the alternative real estate solution. Interesting blog post.

  16. I additionally believe that mesothelioma cancer is a exceptional form of many forms of cancer that is often found in these previously familiar with asbestos. Cancerous cells form while in the mesothelium, which is a safety lining that covers a lot of the body’s body organs. These cells usually form in the lining in the lungs, abdomen, or the sac that really encircles one’s heart. Thanks for expressing your ideas.

  17. WalterCherm表示:

    Their patient education resources are top-tier.
    https://cipropharm24.top/
    They offer international health solutions without borders.

  18. Ebony sex表示:

    We stumbled over here from a different web page and thought I may as well check things out. I like what I see so now i’m following you. Look forward to checking out your web page again.

  19. Victorprima表示:

    A touchstone of international pharmacy standards.
    where to get generic lisinopril without dr prescription
    Everything about medicine.

  20. Jasonzitte表示:

    Their senior citizen discounts are much appreciated.
    order cytotec pill
    A trusted name in international pharmacy circles.

  21. Howdy! This post couldn’t be written any better! Reading through this post reminds me of my previous room mate! He always kept chatting about this. I will forward this article to him. Fairly certain he will have a good read. Many thanks for sharing!

  22. Jasonzitte表示:

    From greeting to checkout, always a pleasant experience.
    buy generic clomid for sale
    The one-stop solution for all international medication requirements.

  23. WalterCherm表示:

    Always leaving this place satisfied.
    https://clomidpharm24.top/
    Helpful, friendly, and always patient.

  24. Tam Hingst表示:

    You made some respectable points there. I seemed on the internet for the issue and found most individuals will associate with with your website.

  25. Dario Ducking表示:

    Greetings! I’ve been reading your website for some time now and finally got the courage to go ahead and give you a shout out from New Caney Tx! Just wanted to say keep up the great job!

  26. you have got an important weblog right here! would you like to make some invite posts on my blog?

  27. Prostitute表示:

    WONDERFUL Post.thanks for share..more wait .. ?

  28. I’d also like to express that most individuals that find themselves with no health insurance are normally students, self-employed and those that are out of work. More than half on the uninsured are really under the age of 35. They do not come to feel they are looking for health insurance as they are young plus healthy. The income is often spent on property, food, in addition to entertainment. Most people that do represent the working class either whole or part time are not made available insurance by means of their jobs so they go without as a result of rising tariff of health insurance in the states. Thanks for the concepts you reveal through this blog.

  29. Wonderful website you have here but I was wondering if you knew of any forums that cover the same topics talked about here? I’d really like to be a part of online community where I can get comments from other experienced people that share the same interest. If you have any suggestions, please let me know. Kudos!

發佈回覆給「Jasonzitte」的留言 取消回覆

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