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

  1. Bob Corker (R-TN) was the only Republican senator to vote against this version of the invoice and it obtained no Democratic Get together assist.

  2. The football staff is among the 12 programs assigned to the 2 Ivy divisions starting in 2020, that are intended to permit weaker applications ineligible for playoff participation to compete primarily towards one another.

  3. Once consumers have the experience of technical analysis graphs, they’re ready to easily find the cost of their transferring market price on the anticipated time.

  4. Pre-want life insurance coverage policies are restricted-premium complete life insurance policies which might be usually purchased by older candidates, although they can be found to everybody.

  5. One thing as simple as bordering a counter in contrasting color tiles to make the sting more seen, rising aisle width from 36 to forty inches, or specifying no-scald faucets and wing-style faucet handles that do not require wrist-twisting, can make a major distinction in your bath’s long-time period usefulness.

  6. Fenders have been prolonged back into the entrance doorways, as on costlier GM makes, and a wise, clear grille changed the considerably busy ’41 face.

  7. Booming industrial sector – The industry sectors within the country are displaying phenomenal development since the last few years that have truly added a lift to the economic system of the nation.

  8. Although there is a competitive export agricultural sector, technological advances have been gradual to enter the protected domestic sector.

  9. I have seen a lot of useful items on your web site about personal computers. However, I have the viewpoint that laptop computers are still not quite powerful sufficiently to be a good selection if you often do tasks that require plenty of power, like video modifying. But for world wide web surfing, statement processing, and a lot other common computer functions they are just great, provided you never mind the tiny screen size. Many thanks for sharing your opinions.

  10. There is noticeably a bundle to learn about this. I assume you made certain nice factors in options also.

  11. Yet another thing I would like to talk about is that as opposed to trying to fit all your online degree courses on days and nights that you finish work (since the majority people are worn out when they get back), try to find most of your sessions on the weekends and only one or two courses in weekdays, even if it means taking some time off your weekend. This is beneficial because on the saturdays and sundays, you will be far more rested plus concentrated on school work. Thanks alot : ) for the different points I have acquired from your site.

  12. certainly like your web-site but you need to check the spelling on several of your posts. Several of them are rife with spelling problems and I find it very bothersome to tell the truth nevertheless I will certainly come back again.

  13. Simply want to say your article is as amazing. The clarity in your post is just spectacular and i could assume you are an expert on this subject. Fine with your permission allow me to grab your RSS feed to keep updated with forthcoming post. Thanks a million and please continue the gratifying work.

  14. While shifting to the northeast, the storm dumped heavy snow and ice over components of the Upper Midwest and Michigan Peninsula by way of 21 December.

  15. Hmm it looks like your website ate my first comment (it was extremely long) so I guess I’ll just sum it up what I wrote and say, I’m thoroughly enjoying your blog. I too am an aspiring blog writer but I’m still new to the whole thing. Do you have any recommendations for rookie blog writers? I’d really appreciate it.

  16. 6050 株価表示:

    Whereas the foremost part of the town falls under three parliamentary constituencies (Chennai North, Chennai Central and Chennai South), the Chennai metropolitan space is unfold throughout five constituencies.

  17. I have learned new things out of your blog post. Yet another thing to I have noticed is that typically, FSBO sellers can reject you. Remember, they can prefer to not ever use your services. But if an individual maintain a reliable, professional partnership, offering assistance and remaining in contact for around four to five weeks, you will usually be able to win a meeting. From there, a house listing follows. Thank you

  18. Someone essentially help to make seriously posts I’d state. That is the very first time I frequented your web page and up to now? I surprised with the analysis you made to make this particular put up incredible. Magnificent activity!

  19. A person essentially help to make seriously posts I would state. This is the first time I frequented your website page and thus far? I amazed with the research you made to create this particular publish amazing. Magnificent job!

  20. California lawmakers approve fracking invoice, NBC Bay Area, 12 Sept.

  21. McGuire, Kara (September 25, 2008).

  22. I used to be recommended this website by way of my cousin. I am not certain whether or not this submit is written by means of him as nobody else recognise such exact about my problem. You are incredible! Thank you!

  23. I?m impressed, I need to say. Really not often do I encounter a blog that?s each educative and entertaining, and let me let you know, you might have hit the nail on the head. Your idea is outstanding; the problem is something that not sufficient persons are speaking intelligently about. I am very comfortable that I stumbled throughout this in my search for one thing referring to this.

  24. Instead, homebuyers get a mortgage called a mortgage from a bank.

  25. I’m very happy to read this. This is the type of manual that needs to be given and not the random misinformation that’s at the other blogs. Appreciate your sharing this best doc.

  26. Howdy! Do you use Twitter? I’d like to follow you if that would be okay. I’m undoubtedly enjoying your blog and look forward to new posts.

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

  28. Many thanks to you for sharing these types of wonderful articles. In addition, the right travel and also medical insurance plan can often reduce those fears that come with visiting abroad. A medical emergency can in the near future become extremely expensive and that’s likely to quickly decide to put a financial problem on the family’s finances. Setting up in place the excellent travel insurance package deal prior to leaving is well worth the time and effort. Thank you

發佈留言

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