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

10,404 Responses

  1. My brother suggested I would possibly like this web site. He was entirely right. This post truly made my day. You cann’t consider simply how much time I had spent for this information! Thank you!

  2. cbd massage表示:

    I have really learned new things by means of your web site. One other thing I’d prefer to say is the fact that newer pc operating systems are inclined to allow more memory to use, but they in addition demand more memory space simply to operate. If a person’s computer could not handle far more memory and the newest software program requires that ram increase, it could be the time to buy a new PC. Thanks

  3. It?s actually a cool and useful piece of information. I am satisfied that you shared this useful info with us. Please keep us up to date like this. Thanks for sharing.

  4. hi!,I like your writing so much! share we communicate more about your post on AOL? I need an expert on this area to solve my problem. May be that’s you! Looking forward to see you.

  5. What i do not realize is actually how you are now not actually much more well-favored than you might be now. You are so intelligent. You realize therefore considerably on the subject of this matter, produced me individually believe it from numerous numerous angles. Its like women and men aren’t fascinated unless it is something to do with Lady gaga! Your own stuffs outstanding. All the time care for it up!

  6. Профессиональный сервисный центр по ремонту бытовой техники с выездом на дом.
    Мы предлагаем: сервисные центры по ремонту техники в москве
    Наши мастера оперативно устранят неисправности вашего устройства в сервисе или с выездом на дом!

  7. bokep jilbab表示:

    That is the appropriate weblog for anyone who needs to search out out about this topic. You notice a lot its almost arduous to argue with you (not that I really would need?HaHa). You undoubtedly put a brand new spin on a topic thats been written about for years. Great stuff, just great!

  8. RobertMef表示:

    ambien indian pharmacy: online otc pharmacy – buy online pharmacy uk

  9. Would you be fascinated by exchanging links?

  10. Thanks for the suggestions you reveal through this web site. In addition, quite a few young women that become pregnant don’t even make an effort to get medical insurance because they are concerned they won’t qualify. Although some states at this moment require that insurers supply coverage regardless of pre-existing conditions. Costs on most of these guaranteed options are usually larger, but when thinking about the high cost of medical treatment it may be any safer way to go to protect your own financial potential.

  11. hello!,I love your writing very a lot! proportion we keep up a correspondence extra approximately your post on AOL? I need a specialist in this space to solve my problem. Maybe that is you! Taking a look forward to look you.

  12. magnificent issues altogether, you simply received a new reader. What may you suggest about your submit that you just made some days in the past? Any sure?

  13. pure cbd oil表示:

    The subsequent time I learn a blog, I hope that it doesnt disappoint me as a lot as this one. I imply, I know it was my option to learn, however I truly thought youd have something attention-grabbing to say. All I hear is a bunch of whining about something that you might fix should you werent too busy looking for attention.

  14. Josephfub表示:

    online shopping pharmacy india Online medicine home delivery india pharmacy

  15. Thanks a lot for your post. I want to comment that the price of car insurance will vary from one policy to another, since there are so many different facets which play a role in the overall cost. Such as, the model and make of the vehicle will have a significant bearing on the cost. A reliable older family vehicle will have a less expensive premium than just a flashy fancy car.

  16. Josephfub表示:

    best online pharmacies in mexico mexican border pharmacies shipping to usa mexican border pharmacies shipping to usa

  17. I am extremely inspired along with your writing abilities and also with the structure for your blog. Is this a paid subject or did you modify it yourself? Anyway stay up the excellent high quality writing, it is uncommon to look a nice blog like this one these days..

  18. Josephfub表示:

    mexican rx online mexican rx online buying prescription drugs in mexico

  19. RobertMef表示:

    п»їlegitimate online pharmacies india: online shopping pharmacy india – best online pharmacy india

  20. MauriceGueda表示:

    п»їlegitimate online pharmacies india: india pharmacy – mail order pharmacy india

  21. We stumbled over here coming from a different website and thought I might as well check things out. I like what I see so now i am following you. Look forward to checking out your web page repeatedly.

  22. MauriceGueda表示:

    buy medicines online in india: reputable indian online pharmacy – best india pharmacy

  23. bokep jilbab表示:

    Hello there, I found your blog via Google while looking for a related topic, your web site came up, it looks good. I’ve bookmarked it in my google bookmarks.

  24. pure cbd oil表示:

    Thanks for the strategies you are sharing on this website. Another thing I would like to say is getting hold of some copies of your credit profile in order to look at accuracy of the detail could be the first action you have to execute in credit improvement. You are looking to freshen your credit history from damaging details mistakes that ruin your credit score.

  25. Howdy very nice website!! Man .. Beautiful .. Wonderful .. I will bookmark your blog and take the feeds additionally?I’m glad to search out numerous useful information right here in the post, we’d like develop extra techniques on this regard, thank you for sharing. . . . . .

  26. MauriceGueda表示:

    medicine in mexico pharmacies: purple pharmacy mexico price list – buying prescription drugs in mexico online

  27. One thing I have actually noticed is always that there are plenty of misconceptions regarding the finance institutions intentions while talking about foreclosed. One fairy tale in particular would be the fact the bank wants your house. The lending company wants your hard earned dollars, not the house. They want the bucks they loaned you together with interest. Averting the bank will simply draw some sort of foreclosed summary. Thanks for your posting.

  28. Your place is valueble for me. Thanks!?

  29. RobertMef表示:

    best online pharmacy to buy cialis: drug store news – claritin d pharmacy counter

  30. Thank you, I have just been looking for information approximately this topic for ages and yours is the best I have came upon so far. But, what concerning the bottom line? Are you sure concerning the source?

發佈留言

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