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

  1. Hello there! This is my first comment here so I just wanted to give a quick shout out and say I truly enjoy reading through your blog posts. Can you suggest any other blogs/websites/forums that deal with the same topics? Thank you!

  2. I don?t even know the way I stopped up here, however I believed this put up used to be great. I don’t realize who you might be however certainly you are going to a well-known blogger if you aren’t already 😉 Cheers!

  3. I was recommended this web site by my cousin. I’m not sure whether this post is written by him as no one else know such detailed about my problem. You are incredible! Thanks!

  4. Hello just wanted to give you a quick heads up. The words in your post seem to be running off the screen in Internet explorer. I’m not sure if this is a formatting issue or something to do with internet browser compatibility but I figured I’d post to let you know. The design and style look great though! Hope you get the issue solved soon. Cheers

  5. Good day! 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 recommendations?

  6. One other issue is when you are in a situation where you will not have a co-signer then you may actually want to try to exhaust all of your financial aid options. You will find many awards and other grants that will supply you with finances to aid with college expenses. Thanks alot : ) for the post.

  7. Thank you for the good writeup. It in truth used to be a amusement account it. Look complicated to more added agreeable from you! However, how could we keep up a correspondence?

  8. I used to be more than happy to search out this internet-site.I wanted to thanks on your time for this wonderful learn!! I undoubtedly having fun with each little bit of it and I’ve you bookmarked to take a look at new stuff you blog post.

  9. An attention-grabbing discussion is worth comment. I think that it’s best to write more on this matter, it may not be a taboo topic but usually people are not sufficient to speak on such topics. To the next. Cheers

  10. Thanks for enabling me to acquire new tips about personal computers. I also have belief that one of the best ways to maintain your notebook computer in primary condition is by using a hard plastic material case, as well as shell, which fits over the top of one’s computer. A lot of these protective gear are model unique since they are manufactured to fit perfectly on the natural housing. You can buy them directly from the owner, or via third party places if they are intended for your laptop, however its not all laptop can have a covering on the market. Yet again, thanks for your guidelines.

  11. Can I simply say what a relief to seek out somebody who actually is aware of what theyre speaking about on the internet. You definitely know how one can deliver an issue to gentle and make it important. Extra individuals must learn this and perceive this side of the story. I cant believe youre no more in style since you undoubtedly have the gift.

  12. Hi! I know this is somewhat off topic but I was wondering if you knew where I could find a captcha plugin for my comment form? I’m using the same blog platform as yours and I’m having difficulty finding one? Thanks a lot!

  13. very nice publish, i certainly love this web site, keep on it

  14. Simply wish to say your article is as astonishing. The clearness for your post is simply spectacular and that i could suppose you’re a professional in this subject. Fine with your permission allow me to take hold of your feed to stay up to date with coming near near post. Thank you a million and please continue the rewarding work.

  15. Thanks for your useful article. Other thing is that mesothelioma cancer is generally a result of the inhalation of materials from asbestos fiber, which is a extremely dangerous material. Its commonly seen among personnel in the structure industry who may have long exposure to asbestos. It is also caused by living in asbestos protected buildings for some time of time, Genetic makeup plays a crucial role, and some people are more vulnerable for the risk compared to others.

  16. xxxสาว7表示:

    I?d must examine with you here. Which is not something I often do! I enjoy studying a submit that may make folks think. Additionally, thanks for allowing me to remark!

  17. One more issue is that video gaming became one of the all-time most important forms of recreation for people of any age. Kids play video games, and adults do, too. The particular XBox 360 is among the favorite video games systems for many who love to have a lot of games available to them, and also who like to play live with other folks all over the world. Thank you for sharing your ideas.

  18. I was just seeking this info for some time. After 6 hours of continuous Googleing, finally I got it in your web site. I wonder what is the lack of Google strategy that don’t rank this kind of informative websites in top of the list. Usually the top web sites are full of garbage.

  19. I was curious if you ever thought of changing the layout of your website? Its very well written; I love what youve got to say. But maybe you could a little more in the way of content so people could connect with it better. Youve got an awful lot of text for only having one or two images. Maybe you could space it out better?

  20. Hey there! This is my 1st comment here so I just wanted to give a quick shout out and say I truly enjoy reading through your posts. Can you recommend any other blogs/websites/forums that cover the same topics? Appreciate it!

  21. I am not sure where you’re getting your info, but good topic. I needs to spend some time learning more or understanding more. Thanks for great information I was looking for this information for my mission.

  22. Hi, Neat post. There is an issue together with your site in internet explorer, would check this? IE still is the market leader and a huge portion of people will omit your fantastic writing because of this problem.

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

  24. I’m not that much of a internet reader to be honest but your sites really nice, keep it up! I’ll go ahead and bookmark your website to come back down the road. Cheers

  25. hello!,I love your writing very much! percentage we keep up a correspondence extra approximately your article on AOL? I require a specialist on this space to solve my problem. Maybe that’s you! Taking a look ahead to peer you.

  26. One thing is that one of the most typical incentives for applying your credit cards is a cash-back or maybe rebate provision. Generally, you get 1-5 back on various expenditures. Depending on the credit card, you may get 1 back again on most expenditures, and 5 in return on acquisitions made using convenience stores, gas stations, grocery stores plus ‘member merchants’.

  27. Thanks for this excellent article. One more thing to mention is that almost all digital cameras are available equipped with the zoom lens that enables more or less of a scene to become included through ‘zooming’ in and out. These kinds of changes in {focus|focusing|concentration|target|the a**** length tend to be reflected while in the viewfinder and on huge display screen on the back of the exact camera.

  28. I have seen many useful factors on your web-site about personal computers. However, I have the opinion that lap tops are still not quite powerful adequately to be a good choice if you generally do jobs that require plenty of power, for example video editing and enhancing. But for internet surfing, word processing, and many other prevalent computer work they are just great, provided you never mind your little friend screen size. Thanks for sharing your ideas.

  29. KevinSounc表示:

    https://slotsiteleri.bid/# slot siteleri

發佈留言

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