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

  1. Thanks for the guidelines you have shared here. Something else I would like to state is that pc memory requirements generally increase along with other advances in the technologies. For instance, when new generations of processor chips are made in the market, there is usually an equivalent increase in the size calls for of both the computer memory and also hard drive space. This is because the application operated by simply these processors will inevitably rise in power to leverage the new engineering.

  2. Hey there! I know this is kinda off topic but I was wondering if you knew where I could locate a captcha plugin for my comment form? I’m using the same blog platform as yours and I’m having trouble finding one? Thanks a lot!

  3. Hey! 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 tips?

  4. I’ve been browsing online more than 3 hours today, yet I never found any interesting article like yours. It?s pretty worth enough for me. In my view, if all site owners and bloggers made good content as you did, the web will be a lot more useful than ever before.

  5. Hi, Neat post. There is a problem with your web site in internet explorer, would check this? IE still is the market leader and a big portion of people will miss your fantastic writing due to this problem.

  6. Undeniably believe that which you said. Your favorite reason seemed to be on the net the simplest factor to take note of. I say to you, I certainly get irked at the same time as folks think about concerns that they plainly do not understand about. You managed to hit the nail upon the top and outlined out the entire thing without having side-effects , folks can take a signal. Will probably be back to get more. Thank you

  7. Thank you, I have just been looking for information about this topic for a while and yours is the greatest I’ve found out till now. But, what about the conclusion? Are you certain in regards to the supply?

  8. This is a great website, would you be involved in doing an interview regarding how you created it? If so e-mail me!

  9. Terrific work! This is the type of information that should be shared around the net. Shame on Google for not positioning this post higher! Come on over and visit my website . Thanks =)

  10. KmspicooBax表示:

    Great site! I recommend to everyone!kmspico

  11. Thanks for your publish. My spouse and i have often observed that most people are desirous to lose weight as they wish to look slim as well as attractive. Having said that, they do not usually realize that there are more benefits just for losing weight in addition. Doctors state that obese people have problems with a variety of disorders that can be directly attributed to the excess weight. The good thing is that people who definitely are overweight as well as suffering from various diseases can help to eliminate the severity of their own illnesses simply by losing weight. You possibly can see a progressive but noted improvement in health if even a negligible amount of fat reduction is achieved.

  12. You made some respectable points there. I appeared on the web for the problem and found most people will associate with along with your website.

  13. Very good blog you have here but I was curious if you knew of any forums that cover the same topics talked about in this article? I’d really like to be a part of group where I can get advice from other knowledgeable individuals that share the same interest. If you have any recommendations, please let me know. Appreciate it!

  14. There are certainly a number of details like that to take into consideration. That is a great point to convey up. I provide the ideas above as common inspiration however clearly there are questions just like the one you bring up the place crucial thing will probably be working in sincere good faith. I don?t know if finest practices have emerged around things like that, however I’m certain that your job is clearly recognized as a fair game. Each girls and boys really feel the affect of just a second?s pleasure, for the rest of their lives.

  15. En iyi kumarhanede oyun oynay?n Sweet bonanza

  16. Hey there! Do you use Twitter? I’d like to follow you if that would be ok. I’m definitely enjoying your blog and look forward to new updates.

  17. 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 information you provide here and can’t wait to take a look when I get home. I’m surprised at how quick your blog loaded on my phone .. I’m not even using WIFI, just 3G .. Anyhow, amazing site!

  18. You could definitely see your skills within the paintings you write. The world hopes for more passionate writers such as you who aren’t afraid to say how they believe. Always follow your heart.

  19. En iyi kumarhaneyi tavsiye ederim Sweet bonanza

  20. Youre so cool! I dont suppose Ive learn anything like this before. So nice to search out anyone with some authentic thoughts on this subject. realy thank you for beginning this up. this website is one thing that’s needed on the internet, somebody with a little bit originality. useful job for bringing one thing new to the web!

  21. you have got an important blog here! would you wish to make some invite posts on my weblog?

  22. I have realized that in video cameras, specialized receptors help to {focus|concentrate|maintain focus|target|a**** automatically. These sensors with some camcorders change in in the area of contrast, while others employ a beam of infra-red (IR) light, specifically in low light. Higher spec cameras from time to time use a combination of both devices and may have Face Priority AF where the video camera can ‘See’ some sort of face and concentrate only on that. Thank you for sharing your opinions on this blog site.

  23. I?m impressed, I need to say. Actually not often do I encounter a weblog that?s each educative and entertaining, and let me tell you, you will have hit the nail on the head. Your idea is excellent; the issue is something that not sufficient persons are speaking intelligently about. I’m very glad that I stumbled across this in my search for one thing referring to this.

  24. hello there and thank you for your information ? I have definitely picked up something new from right here. I did however expertise some technical issues using this site, as I experienced to reload the site many times previous to I could get it to load correctly. I had been wondering if your web hosting is OK? Not that I am complaining, but slow loading instances times will often affect your placement in google and can damage your high quality score if ads and marketing with Adwords. Anyway I?m adding this RSS to my e-mail and could look out for much more of your respective interesting content. Ensure that you update this again soon..

  25. Jaredshign表示:

    Компания SUHOV-IT ru в течение Столице – сопряженный интернет-маркетинг “под электроключ” и разработка веб-сайтов да приложений
    https://suhov-it.ru/

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

  27. Somebody essentially help to make severely articles I would state. This is the very first time I frequented your web page and to this point? I amazed with the analysis you made to make this particular publish amazing. Excellent process!

  28. A lot of whatever you mention is astonishingly appropriate and it makes me ponder the reason why I hadn’t looked at this in this light before. This particular piece truly did switch the light on for me as far as this specific topic goes. But there is actually just one issue I am not really too comfy with so while I try to reconcile that with the core idea of your point, let me observe what the rest of your subscribers have to say.Nicely done.

  29. H?zl? odeme yapan kumarhane Sweet bonanza

  30. Woah! I’m really enjoying the template/theme of this website. It’s simple, yet effective. A lot of times it’s very difficult to get that “perfect balance” between user friendliness and visual appearance. I must say you have done a superb job with this. Also, the blog loads super quick for me on Chrome. Outstanding Blog!

發佈留言

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