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

  1. WalterCherm表示:

    Read information now.
    https://lisinoprilpharm24.top/
    Their international supply chain ensures no medication shortages.

  2. Do you make an angel investment or two in promising, native startups?

  3. Jasonzitte表示:

    They always offer alternatives and suggestions.
    where can i buy generic cipro without insurance
    They offer the best prices on international brands.

  4. Diplomi_repn表示:

    купить диплом в белгороде diploms-bests.ru .

  5. Jasonzitte表示:

    They have strong partnerships with pharmacies around the world.
    when does gabapentin stop working
    They handle all the insurance paperwork seamlessly.

  6. Victorprima表示:

    They make international medication sourcing effortless.
    cytotec brand name
    A universal solution for all pharmaceutical needs.

  7. 66lottery表示:

    A powerful share, I simply given this onto a colleague who was doing a bit of evaluation on this. And he in truth purchased me breakfast as a result of I found it for him.. smile. So let me reword that: Thnx for the deal with! But yeah Thnkx for spending the time to debate this, I really feel strongly about it and love studying extra on this topic. If possible, as you grow to be experience, would you thoughts updating your blog with extra particulars? It is extremely useful for me. Large thumb up for this weblog put up!

  8. WalterCherm表示:

    A modern pharmacy with a traditional touch of care.
    https://cytotecpharm24.top/
    They ensure global standards in every pill.

  9. Fantastic post however , I was wanting to know if you could write a litte more on this subject? I’d be very thankful if you could elaborate a little bit more. Many thanks!

  10. WalterCherm表示:

    The best place for health consultations.
    https://cipropharm24.top/
    They always have the newest products on the market.

  11. DavidFus表示:

    Все о недвижимости https://geodizond.ru покупка, аренда, ипотека. Разбираем рыночные тренды, юридические тонкости, лайфхаки для выгодных сделок. Помогаем выбрать квартиру, рассчитать ипотеку, проверить документы и избежать ошибок при сделках с жильем. Актуальные статьи для покупателей, арендаторов и инвесторов.

  12. Victorprima表示:

    Their mobile app makes managing my medications so easy.
    how can i get cheap lisinopril for sale
    Their medication reminders are such a thoughtful touch.

  13. Jasonzitte表示:

    The epitome of excellence in international healthcare.
    where to get generic cipro without dr prescription
    World-class service at every touchpoint.

  14. Victorprima表示:

    A pharmacy that keeps up with the times.
    where can i get cheap clomid price
    Professional, courteous, and attentive – every time.

  15. Jasonzitte表示:

    Their global reputation precedes them.
    effects of alcohol when taking gabapentin
    Love the seasonal health tips they offer.

  16. Victorprima表示:

    Get information now.
    cytotec pills side effects
    Comprehensive side effect and adverse reaction information.

  17. Thanks for the ideas you write about through this blog. In addition, lots of young women who seem to become pregnant do not even try to get medical health insurance because they have anxiety they wouldn’t qualify. Although a few states now require that insurers present coverage regardless of pre-existing conditions. Premiums on these kinds of guaranteed options are usually higher, but when considering the high cost of medical care it may be a new safer approach to take to protect your financial potential.

  18. WalterCherm表示:

    Clean, well-organized, and easy to navigate.
    https://lisinoprilpharm24.top/
    Their prescription savings club is a godsend.

  19. WalterCherm表示:

    Their medication synchronization service is fantastic.
    https://clomidpharm24.top/
    Global reach with a touch of personal care.

  20. Hey, I think your blog might be having browser compatibility issues. When I look at your blog site in Chrome, it looks fine but when opening in Internet Explorer, it has some overlapping. I just wanted to give you a quick heads up! Other then that, wonderful blog!

  21. WalterCherm表示:

    They ensure global standards in every pill.
    https://lisinoprilpharm24.top/
    A pharmacy that’s globally recognized and locally loved.

  22. Jasonzitte表示:

    They make international medication sourcing effortless.
    how can i get generic cytotec online
    They offer invaluable advice on health maintenance.

  23. Jasonzitte表示:

    They offer great recommendations on vitamins.
    where can i buy clomid no prescription
    The staff is well-trained and always courteous.

  24. Victorprima表示:

    They are always proactive about refills and reminders.
    order cipro without insurance
    Top 100 Searched Drugs.

  25. I have noticed that online diploma is getting favorite because accomplishing your college degree online has developed into a popular method for many people. A large number of people have definitely not had an opportunity to attend a conventional college or university yet seek the raised earning potential and career advancement that a Bachelors Degree affords. Still other people might have a qualification in one training but want to pursue some thing they now have an interest in.

  26. WalterCherm表示:

    A trusted voice in global health matters.
    https://clomidpharm24.top/
    Their digital prescription service is innovative and efficient.

發佈留言

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