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

19,964 Responses

  1. running man 4表示:

    I do not even know how I ended up here, but I thought this post was great. I don’t know who you are but certainly you are going to a famous blogger if you are not already 😉 Cheers!

  2. Howdy! Someone in my Facebook group shared this site with us so I came to look it over. I’m definitely enjoying the information. I’m book-marking and will be tweeting this to my followers! Excellent blog and superb design and style.

  3. I have been absent for some time, but now I remember why I used to love this web site. Thank you, I?ll try and check back more often. How frequently you update your website?

  4. I loved as much as you’ll receive carried out right here. The sketch is tasteful, your authored material stylish. nonetheless, you command get got an impatience over that you wish be delivering the following. unwell unquestionably come more formerly again since exactly the same nearly a lot often inside case you shield this hike.

  5. Thanks for the new things you have discovered in your post. One thing I want to discuss is that FSBO interactions are built over time. By bringing out yourself to the owners the first saturday and sunday their FSBO is usually announced, prior to masses start off calling on Thursday, you develop a good interconnection. By mailing them equipment, educational products, free records, and forms, you become a good ally. If you take a personal fascination with them and also their circumstance, you develop a solid connection that, on many occasions, pays off once the owners decide to go with an adviser they know as well as trust — preferably you.

  6. When I originally commented I clicked the “Notify me when new comments are added” checkbox and now each time a comment is added I get three e-mails with the same comment. Is there any way you can remove people from that service? Cheers!

  7. Hey! Do you know if they make any plugins to assist with Search Engine Optimization? I’m trying to get my blog to rank for some targeted keywords but I’m not seeing very good success. If you know of any please share. Appreciate it!

  8. I do not even know the way I stopped up here, however I believed this submit was once great. I do not recognize who you’re however definitely you’re going to a famous blogger should you aren’t already 😉 Cheers!

  9. Today, taking into consideration the fast way of living that everyone leads, credit cards have a huge demand throughout the market. Persons out of every field are using the credit card and people who aren’t using the credit card have prepared to apply for one. Thanks for discussing your ideas in credit cards.

  10. It’s best to take part in a contest for the most effective blogs on the web. I’ll suggest this site!

  11. Wow! This can be one particular of the most beneficial blogs We’ve ever arrive across on this subject. Basically Great. I’m also a specialist in this topic so I can understand your hard work.

  12. Отличный сайт! Всем рекомендую!портрет на холсте в Тюмени

  13. My coder is trying to convince me to move to .net from PHP. I have always disliked the idea because of the costs. But he’s tryiong none the less. I’ve been using Movable-type on several websites for about a year and am concerned about switching to another platform. I have heard great things about blogengine.net. Is there a way I can import all my wordpress posts into it? Any help would be really appreciated!

  14. hey there and thank you for your info ? I have certainly picked up anything new from right here. I did however expertise some technical issues using this web site, since I experienced to reload the site lots of times previous to I could get it to load correctly. I had been wondering if your web hosting is OK? Not that I’m complaining, but slow loading instances times will very frequently 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 email and could look out for a lot more of your respective fascinating content. Make sure you update this again soon..

  15. blooming 2023表示:

    Your place is valueble for me. Thanks!?

  16. Drstobeese表示:

    can you buy viagra from the pharmacy: drug store news – tylenol 3 online pharmacy

  17. Drstobeese表示:

    pharmacy2u co uk viagra: rx pharmacy coupons – cialis xlpharmacy

  18. I just could not depart your website prior to suggesting that I extremely enjoyed the standard info a person provide for your visitors? Is going to be back often in order to check up on new posts

  19. connection表示:

    Thanks for your personal marvelous posting! I definitely enjoyed reading it, you might be a great author.I will be sure to bookmark your blog and will eventually come back sometime soon. I want to encourage you to ultimately continue your great posts, have a nice afternoon!

  20. Ehrhbn表示:

    buy mestinon without prescription – order imuran 50mg online cheap imuran 25mg oral

  21. Lazrnat表示:

    Добрый день!
    Мы можем предложить дипломы психологов, юристов, экономистов и прочих профессий по приятным ценам.
    ariom.ru/fo/t14412

  22. One thing I’ve noticed is the fact that there are plenty of myths regarding the lenders intentions if talking about foreclosure. One myth in particular is the bank wants your house. The lender wants your hard earned cash, not the home. They want the amount of money they lent you having interest. Staying away from the bank is only going to draw any foreclosed summary. Thanks for your article.

  23. What i do not realize is in reality how you are not really a lot more neatly-preferred than you may be right now. You’re very intelligent. You recognize therefore significantly in the case of this matter, made me in my view consider it from so many various angles. Its like men and women aren’t fascinated except it is something to do with Woman gaga! Your own stuffs nice. Always deal with it up!

  24. My partner and I stumbled over here different web address and thought I may as well check things out. I like what I see so now i am following you. Look forward to checking out your web page yet again.

  25. Hi would you mind stating which blog platform you’re working with? I’m looking to start my own blog soon but I’m having a difficult time selecting between BlogEngine/Wordpress/B2evolution and Drupal. The reason I ask is because your layout seems different then most blogs and I’m looking for something completely unique. P.S Sorry for getting off-topic but I had to ask!

  26. Thanks for your exciting article. One other problem is that mesothelioma cancer is generally the result of the breathing of fibres from asbestos fiber, which is a positivelly dangerous material. It is commonly witnessed among employees in the construction industry with long exposure to asbestos. It can also be caused by living in asbestos protected buildings for a long time of time, Inherited genes plays an important role, and some consumers are more vulnerable to the risk when compared with others.

  27. Aw, this was a very nice post. In thought I would like to put in writing like this moreover ? taking time and actual effort to make an excellent article? but what can I say? I procrastinate alot and not at all appear to get one thing done.

  28. my boss 2024表示:

    Hi there, simply was aware of your blog thru Google, and found that it’s really informative. I am gonna watch out for brussels. I will appreciate in the event you proceed this in future. Many people will probably be benefited out of your writing. Cheers!

  29. Thanks for your posting. I also think that laptop computers have grown to be more and more popular today, and now are usually the only type of computer used in a household. The reason is that at the same time potentially they are becoming more and more reasonably priced, their processing power keeps growing to the point where they are as potent as pc’s out of just a few years ago.

  30. Once I initially commented I clicked the -Notify me when new feedback are added- checkbox and now each time a comment is added I get four emails with the identical comment. Is there any method you’ll be able to take away me from that service? Thanks!

發佈留言

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