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

35,300 Responses

  1. alarme Ajax表示:

    Thanks for your posting. One other thing is the fact individual states have their particular laws of which affect house owners, which makes it very difficult for the the nation’s lawmakers to come up with a whole new set of recommendations concerning foreclosure on householders. The problem is that a state has own guidelines which may have interaction in a negative manner with regards to foreclosure procedures.

  2. qq88表示:

    Thanks for the sensible critique. Me and my neighbor were just preparing to do a little research on this. We got a grab a book from our area library but I think I learned more from this post. I am very glad to see such magnificent info being shared freely out there.

  3. Cool blog! Is your theme custom made or did you download it from somewhere? A theme like yours with a few simple adjustements would really make my blog shine. Please let me know where you got your theme. Kudos

  4. Richardaudit表示:

    https://zithpharmonline.com/# ZithPharmOnline

  5. qq88表示:

    I have noticed that clever real estate agents everywhere are getting set to FSBO ***********. They are realizing that it’s in addition to placing a sign in the front yard. It’s really pertaining to building associations with these retailers who someday will become purchasers. So, once you give your time and efforts to helping these traders go it alone — the “Law regarding Reciprocity” kicks in. Thanks for your blog post.

  6. LanceFen表示:

    AmOnlinePharm: AmOnlinePharm – AmOnlinePharm

  7. BrianTom表示:

    Lisin Express url lisinopril hctz prescription Lisin Express

  8. bet88dog表示:

    I loved as much as you’ll receive carried out right here. The sketch is tasteful, your authored subject matter stylish. nonetheless, you command get bought an nervousness over that you wish be delivering the following. unwell unquestionably come further formerly again as exactly the same nearly a lot often inside case you shield this increase.

  9. Thanks for your tips about this blog. A single thing I wish to say is always that purchasing electronic devices items on the Internet is nothing new. The fact is, in the past few years alone, the market for online electronics has grown noticeably. Today, you can find practically any specific electronic gadget and product on the Internet, from cameras plus camcorders to computer pieces and video games consoles.

  10. qq88表示:

    I was suggested this blog by my cousin. I am now not sure whether this put up is written via him as nobody else recognise such distinctive approximately my problem. You are wonderful! Thank you!

  11. bet88dog表示:

    you are really a good webmaster. The web site loading speed is incredible. It seems that you are doing any unique trick. Also, The contents are masterpiece. you have done a great job on this topic!

  12. qq88表示:

    I’m really enjoying the design and layout of your website. It’s a very easy on the eyes which makes it much more pleasant for me to come here and visit more often. Did you hire out a developer to create your theme? Great work!

  13. bet88dog表示:

    Howdy! Do you know if they make any plugins to protect against hackers? I’m kinda paranoid about losing everything I’ve worked hard on. Any suggestions?

  14. qq88表示:

    Hey! I know this is kinda off topic but I was wondering which blog platform are you using for this site? I’m getting fed up of WordPress because I’ve had issues with hackers and I’m looking at options for another platform. I would be awesome if you could point me in the direction of a good platform.

  15. Michaelscoob表示:

    AmOnlinePharm: amoxicillin 250 mg – amoxicillin generic

  16. very good publish, i actually love this website, keep on it

  17. Danieldrymn表示:

    AmOnlinePharm: amoxicillin over the counter in canada – amoxicillin 500 mg online

  18. Thanks, I have recently been looking for info about this topic for ages and yours is the best I’ve found so far.

  19. qq88表示:

    You made some decent factors there. I looked on the internet for the difficulty and located most people will associate with along with your website.

  20. qq88表示:

    Thanks for your content. One other thing is that if you are promoting your property by yourself, one of the troubles you need to be alert to upfront is how to deal with house inspection records. As a FSBO supplier, the key about successfully shifting your property and saving money in real estate agent commissions is knowledge. The more you recognize, the easier your property sales effort are going to be. One area that this is particularly important is assessments.

  21. bet88dog表示:

    Oh my goodness! a tremendous article dude. Thanks However I’m experiencing difficulty with ur rss . Don?t know why Unable to subscribe to it. Is there anybody getting equivalent rss drawback? Anybody who is aware of kindly respond. Thnkx

  22. Michaelscoob表示:

    ZithPharmOnline: ZithPharmOnline – ZithPharmOnline

  23. great points altogether, you simply gained a brand new reader. What would you recommend about your post that you made a few days ago? Any positive?

  24. bet88dog表示:

    Youre so cool! I dont suppose Ive read anything like this before. So nice to find any person with some unique ideas on this subject. realy thanks for starting this up. this website is something that’s wanted on the web, someone with slightly originality. helpful job for bringing something new to the internet!

  25. Richardaudit表示:

    https://zithpharmonline.shop/# ZithPharmOnline

  26. qq88表示:

    As I web-site possessor I believe the content matter here is rattling excellent , appreciate it for your efforts. You should keep it up forever! Best of luck.

  27. qq88表示:

    you’re in point of fact a just right webmaster. The web site loading pace is incredible. It seems that you are doing any unique trick. In addition, The contents are masterpiece. you’ve performed a wonderful job on this matter!

  28. alarme Ajax表示:

    Greetings from Los angeles! I’m bored to death at work so I decided to browse your website on my iphone during lunch break. I enjoy the knowledge you present here and can’t wait to take a look when I get home. I’m amazed at how fast your blog loaded on my mobile .. I’m not even using WIFI, just 3G .. Anyhow, superb site!

  29. bet88dog表示:

    Thanks for the concepts you have shared here. In addition, I believe there are a few factors which keep your car insurance premium all the way down. One is, to think about buying vehicles that are within the good report on car insurance businesses. Cars which might be expensive are usually more at risk of being snatched. Aside from that insurance is also depending on the value of your car, so the more costly it is, then higher a premium you spend.

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

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

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