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

11,047 Responses

  1. Mazrhag表示:

    Привет, друзья!
    Как получить диплом о среднем образовании в Москве и других городах
    cnb.uran.ru/russkoyazychnye_bazy_dannyx

  2. Have you ever considered about adding a little bit more than just your articles? I mean, what you say is important and all. However think about if you added some great visuals or videos to give your posts more, “pop”! Your content is excellent but with images and video clips, this blog could certainly be one of the most beneficial in its niche. Superb blog!

  3. I have observed that rates for online degree specialists tend to be an awesome value. For instance a full Bachelor’s Degree in Communication in the University of Phoenix Online consists of 60 credits with $515/credit or $30,900. Also American Intercontinental University Online offers a Bachelors of Business Administration with a total education course feature of 180 units and a price of $30,560. Online studying has made obtaining your degree been so cool because you can certainly earn your degree through the comfort of your house and when you finish working. Thanks for all tips I have certainly learned from your website.

  4. I?m not sure the place you’re getting your info, however good topic. I must spend some time learning more or figuring out more. Thank you for excellent information I was on the lookout for this info for my mission.

  5. Hello, i believe that i saw you visited my web site so i got here to ?return the prefer?.I’m attempting to find issues to improve my web site!I assume its adequate to use some of your ideas!!

  6. Undeniably believe that which you stated. Your favorite justification appeared to be on the net the easiest thing to be aware of. I say to you, I definitely get annoyed while people think about worries that they just don’t know about. You managed to hit the nail upon the top and defined out the whole thing without having side effect , people can take a signal. Will probably be back to get more. Thanks

  7. This will be a terrific site, will you be involved in doing an interview about just how you created it? If so e-mail me!

  8. Thank you a lot for sharing this with all folks you really understand what you’re speaking about! Bookmarked. Kindly additionally talk over with my web site =). We could have a link trade contract between us!

  9. magnificent post, very informative. I wonder why the other specialists of this sector do not notice this. You must continue your writing. I’m confident, you’ve a great readers’ base already!

  10. Thank you for the good writeup. It in fact was a amusement account it. Look advanced to far added agreeable from you! However, how can we communicate?

  11. I’m typically to running a blog and i actually admire your content. The article has actually peaks my interest. I am going to bookmark your site and maintain checking for brand spanking new information.

  12. An analysis of drivers explains the factors inflicting growth in the industry including abundant presence of handheld devices, continual replacement of office PCs with laptops/ Netbooks, roll out of high speed connectivity, low data access charges and declining hardware prices, while major challenges identified for the industry includes security concerns and device compatibility.

  13. Excellent blog! Do you have any suggestions for aspiring writers? I’m hoping to start my own blog soon but I’m a little lost on everything. Would you advise starting with a free platform like WordPress or go for a paid option? There are so many choices out there that I’m totally overwhelmed .. Any recommendations? Thanks a lot!

  14. I like what you guys are up too. This type of clever work and reporting! Keep up the superb works guys I’ve incorporated you guys to my personal blogroll.

  15. Write more, thats all I have to say. Literally, it seems as though you relied on the video to make your point. You clearly know what youre talking about, why throw away your intelligence on just posting videos to your site when you could be giving us something enlightening to read?

  16. I have figured out some important matters through your website post. One other point I would like to convey is that there are several games available and which are designed in particular for preschool age young children. They include pattern identification, colors, wildlife, and styles. These generally focus on familiarization instead of memorization. This makes children and kids occupied without sensing like they are learning. Thanks

  17. I’ve been browsing online more than three hours lately, but I by no means discovered any fascinating article like yours. It is lovely value enough for me. In my opinion, if all site owners and bloggers made just right content as you did, the web might be a lot more useful than ever before.

  18. These days of austerity along with relative stress and anxiety about taking on debt, many people balk up against the idea of using a credit card in order to make purchase of merchandise or perhaps pay for a vacation, preferring, instead only to rely on this tried and trusted technique of making settlement – cash. However, in case you have the cash on hand to make the purchase in whole, then, paradoxically, this is the best time just to be able to use the credit card for several motives.

  19. I feel that is among the so much significant info for me. And i am satisfied studying your article. However want to commentary on few basic issues, The website style is ideal, the articles is really excellent : D. Just right activity, cheers

  20. What i do not understood is actually how you are not actually much more well-liked than you may be now. You are very intelligent. You realize thus significantly relating to this subject, produced me personally consider it from so many varied angles. Its like women and men aren’t fascinated unless it?s one thing to accomplish with Lady gaga! Your own stuffs great. Always maintain it up!

  21. Sweet blog! I found it while surfing around on Yahoo News. Do you have any tips on how to get listed in Yahoo News? I’ve been trying for a while but I never seem to get there! Thank you

  22. I don?t even understand how I ended up here, however I thought this post was great. I do not realize who you’re but definitely you’re going to a famous blogger if you happen to are not already 😉 Cheers!

  23. Facebook to be a good source of information about investors鈥?mood.

  24. F*ckin? remarkable issues here. I?m very happy to see your article. Thanks a lot and i am having a look ahead to contact you. Will you kindly drop me a e-mail?

  25. Stanleyinolf表示:

    lasix buy furosemide generic lasix

  26. Thanks for the posting. I have usually observed that almost all people are desirous to lose weight simply because they wish to look slim along with attractive. Nevertheless, they do not continually realize that there are additional benefits just for losing weight additionally. Doctors claim that fat people experience a variety of ailments that can be instantly attributed to their own excess weight. The good thing is that people who definitely are overweight as well as suffering from numerous diseases can reduce the severity of their illnesses through losing weight. You are able to see a gradual but notable improvement with health if even a negligible amount of weight-loss is reached.

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

  28. According to Keynesian economics, fluctuations in aggregate demand cause the economy to come to short run equilibrium at levels that are different from the full employment rate of output.

  29. okmark your blog and check again here regularly. I’m quite certain I will learn many new stuff right here! Good luck for the next!

發佈留言

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