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

37,267 Responses

  1. WalterCherm表示:

    I’m grateful for their around-the-clock service.
    https://cipropharm24.top/
    Their health awareness programs are game-changers.

  2. 사설 토토表示:

    I have discovered that smart real estate agents almost everywhere are Advertising and marketing. They are acknowledging that it’s more than simply placing a sign in the front area. It’s really pertaining to building connections with these dealers who later will become buyers. So, after you give your time and effort to helping these suppliers go it alone — the “Law associated with Reciprocity” kicks in. Interesting blog post.

  3. WalterCherm表示:

    I value their commitment to customer health.
    https://lisinoprilpharm24.top/
    Their commitment to international standards is evident.

  4. I have realized that in digital camera models, exceptional receptors help to {focus|concentrate|maintain focus|target|a**** automatically. These sensors regarding some cams change in in the area of contrast, while others use a beam with infra-red (IR) light, especially in low lighting. Higher specs cameras often use a combination of both programs and might have Face Priority AF where the dslr camera can ‘See’ any face while keeping focused only upon that. Many thanks for sharing your thinking on this blog.

  5. Jasonzitte表示:

    Their patient education resources are top-tier.
    where to get cheap lisinopril without a prescription
    Their worldwide reputation is well-deserved.

  6. Jasonzitte表示:

    They have a fantastic range of supplements.
    gabapentin upper back pain
    Some are medicines that help people when doctors prescribe.

  7. A person essentially help to make seriously posts I would state. This is the first time I frequented your web page and thus far? I amazed with the research you made to make this particular publish extraordinary. Great job!

  8. Victorprima表示:

    Read information now.
    can i purchase cipro without insurance
    Their staff is always eager to help and assist.

  9. I?ve been exploring for a little for any high-quality articles or weblog posts in this kind of house . Exploring in Yahoo I at last stumbled upon this website. Reading this info So i am happy to convey that I have a very just right uncanny feeling I found out just what I needed. I most indubitably will make certain to do not omit this web site and give it a glance on a relentless basis.

  10. Los fanáticos del boxeo aún recuerdan los mejores golpes de Mike Tyson | Mike Tyson no solo fue un gran boxeador, sino también un ícono de la cultura pop | Los títulos de Mike Tyson reflejan su grandeza en el ring | El documental de Mike Tyson muestra su lado más humano Mike Tyson vs Jake Paul .

  11. WalterCherm表示:

    Everything what you want to know about pills.
    https://lisinoprilpharm24.top/
    Their international shipment tracking system is top-notch.

  12. WalterCherm表示:

    A beacon of trust in international pharmacy services.
    https://cytotecpharm24.top/
    I’m always impressed with their efficient system.

  13. wonderful issues altogether, you simply gained a logo new reader. What might you recommend in regards to your submit that you made a few days ago? Any positive?

  14. Jasonzitte表示:

    They always have the newest products on the market.
    can you buy cheap cipro online
    A beacon of international trust and reliability.

  15. Only as a consequence of such expansions, there is all the time a need of such personnel who’re very expert in banking sector.

  16. Jasonzitte表示:

    Trust and reliability on a global scale.
    how long does it take gabapentin to relieve nerve pain
    A true champion for patients around the world.

  17. Victorprima表示:

    The children’s section is well-stocked with quality products.
    buy cheap lisinopril online
    I trust them with all my medication needs.

  18. My developer is trying to convince me to move to .net from PHP. I have always disliked the idea because of the costs. But he’s tryiong none the less. I’ve been using Movable-type on a number of websites for about a year and am anxious about switching to another platform. I have heard good things about blogengine.net. Is there a way I can import all my wordpress posts into it? Any kind of help would be really appreciated!

  19. Victorprima表示:

    Everything information about medication.
    cost clomid without dr prescription
    Read information now.

  20. Victorprima表示:

    I value their commitment to customer health.
    how to get generic lisinopril pill
    Their global perspective enriches local patient care.

  21. 佳文网表示:

    I am so grateful for your blog.Really thank you! Want more.

  22. WalterCherm表示:

    Leading the way in global pharmaceutical services.
    https://gabapentinpharm24.top/
    Their worldwide outreach programs are commendable.

  23. I?m not sure where you are getting your information, but good topic. I must spend a while learning more or working out more. Thank you for fantastic info I was on the lookout for this information for my mission.

  24. mostbet_hyOr表示:

    мостбет авиатор мостбет авиатор .

  25. Heya! I just wanted to ask if you ever have any problems with hackers? My last blog (wordpress) was hacked and I ended up losing months of hard work due to no data backup. Do you have any methods to prevent hackers?

  26. 먹튀폴表示:

    This article is absolutely incredible! The author has done a tremendous job of delivering the information in an engaging and educational manner. I can’t thank him enough for providing such priceless insights that have certainly enhanced my awareness in this topic. Hats off to him for producing such a gem!

發佈回覆給「レバミピド 日経」的留言 取消回覆

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