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

38,088 Responses

  1. I really like what you guys tend to be up too. This kind of clever work and reporting! Keep up the fantastic works guys I’ve incorporated you guys to my personal blogroll.

  2. BillieLet表示:

    pharmacie en ligne avec ordonnance: Pharmacies en ligne certifiees – pharmacie en ligne sans ordonnance pharmafst.com

  3. One thing is the fact that one of the most frequent incentives for utilizing your credit card is a cash-back and also rebate supply. Generally, you’re going to get 1-5 back upon various acquisitions. Depending on the card, you may get 1 again on most buying, and 5 in return on buying made on convenience stores, gas stations, grocery stores as well as ‘member merchants’.

  4. Thanks for your posting. My spouse and i have usually noticed that many people are eager to lose weight because they wish to show up slim and also attractive. Having said that, they do not always realize that there are more benefits just for losing weight in addition. Doctors assert that overweight people come across a variety of ailments that can be instantly attributed to their particular excess weight. The great news is that people who sadly are overweight as well as suffering from diverse diseases can reduce the severity of their particular illnesses simply by losing weight. You are able to see a steady but notable improvement with health if even a minor amount of fat loss is accomplished.

  5. Thanks for the ideas you have contributed here. In addition, I believe there are a few factors that really keep your car insurance premium decrease. One is, to contemplate buying automobiles that are in the good listing of car insurance firms. Cars which are expensive are usually more at risk of being robbed. Aside from that insurance is also in accordance with the value of your car or truck, so the more costly it is, then higher a premium you pay.

  6. Howdy! 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?

  7. BradleyJaire表示:

    Acheter Cialis: Acheter Cialis 20 mg pas cher – Acheter Viagra Cialis sans ordonnance tadalmed.shop

  8. F*ckin? amazing things here. I am very glad to see your post. Thanks a lot and i’m looking forward to contact you. Will you kindly drop me a mail?

  9. Peterclada表示:

    Cialis generique prix Cialis generique prix Cialis generique prix tadalmed.com

  10. You could certainly see your skills in the paintings you write. The sector hopes for even more passionate writers like you who are not afraid to say how they believe. At all times follow your heart.

  11. Hi would you mind stating which blog platform you’re using? I’m planning to start my own blog in the near future but I’m having a difficult time making a decision between BlogEngine/Wordpress/B2evolution and Drupal. The reason I ask is because your design and style 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!

  12. Bernardshoor表示:

    pharmacie en ligne avec ordonnance: Medicaments en ligne livres en 24h – pharmacies en ligne certifiГ©es pharmafst.com

  13. Carlospoogy表示:

    Mindful wellness challenges
    If you’re the type of person who thrives on challenges and pushing your limits, this doesn’t mean you need to shy away from wellness challenges altogether. But before diving in, take a step back and ask yourself if you’re pursuing the challenge for the right reasons, McGregor said.
    velodrome finance
    Some people want to try these challenges because they believe something is missing from their life, and they’re looking to attain “worth” or receive validation, McGregor noted.

    A good way to assess your motivation is by considering whether the challenge will benefit your health or if it’s about showcasing your accomplishments on social media or some other reason.

    Before trying any new trend, make sure you have the foundation to handle it and be aware of any potential risks, McGregor said.

    For casual runners, this might mean signing up for a 5K but building your endurance gradually while incorporating other strength training exercises into your routine. For more intense challenges, such as a marathon, McGregor encourages people to consult with professionals or a coach who can monitor your progress and condition along the way.

    Focusing on sustainable habits
    Both McGregor and Curran emphasize the importance of fostering sustainable health habits before embarking on more extreme challenges.

    Rather than chasing the idea of being “healthy,” McGregor suggests focusing on actual healthful behaviors and starting small.

    If you’re a highly sedentary person and want to add more movement to your day, try doing lunges while brushing your teeth or taking short walks throughout your typical routine.

  14. Bernardshoor表示:

    kamagra oral jelly: Kamagra Commander maintenant – kamagra en ligne

  15. Valuable info. Lucky me I found your site by accident, and I am shocked why this accident did not happened earlier! I bookmarked it.

  16. Robertfap表示:

    http://kamagraprix.com/# kamagra oral jelly

  17. Howdy! I know this is kinda off topic but I was wondering if you knew where I could get 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!

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

  19. Обзоры шторных решений для загородных домов, при помощи красивых штор, подбираем шторы для загородного дома, стильный дизайн штор, стиль и удобство, современные материалы для штор, шторы для приватности, стильные решения для штор, выбираем шторы для загородной гостиной, примеры оформления окон с шторами, шторы из натуральных материалов для уюта, современные механизмы для штор, подбираем шторы под интерьер, украшение окон штором, создайте атмосферу с подходящими шторами, лучшие идеи для оформления окон, сравнение видов штор для дачи, подчеркните архитектуру дома с помощью штор, шторы для зимнего уюта в загородном доме
    шторы в загородном доме шторы в загородном доме .

  20. Thank you for the sensible critique. Me & my neighbor were just preparing to do a little research on this. We got a grab a book from our local library but I think I learned more from this post. I’m very glad to see such magnificent info being shared freely out there.

  21. of course like your web site but you have to check the spelling on quite a few of your posts. Several of them are rife with spelling issues and I find it very troublesome to tell the reality however I?ll definitely come back again.

  22. Many thanks to you for sharing these kinds of wonderful threads. In addition, the best travel plus medical insurance program can often eradicate those considerations that come with visiting abroad. A new medical emergency can shortly become expensive and that’s sure to quickly set a financial stress on the family finances. Putting in place the perfect travel insurance program prior to leaving is definitely worth the time and effort. Thanks a lot

  23. Furthermore, i believe that mesothelioma cancer is a exceptional form of cancer that is often found in individuals previously exposed to asbestos. Cancerous cells form while in the mesothelium, which is a defensive lining that covers almost all of the body’s bodily organs. These cells normally form inside lining of the lungs, mid-section, or the sac which encircles the heart. Thanks for discussing your ideas.

  24. Hey! Quick question that’s totally off topic. Do you know how to make your site mobile friendly? My website looks weird when viewing from my iphone 4. I’m trying to find a template or plugin that might be able to correct this problem. If you have any suggestions, please share. With thanks!

  25. Robertfap表示:

    https://tadalmed.com/# Tadalafil sans ordonnance en ligne

  26. I have been exploring for a little bit for any high-quality articles or blog posts on this kind of area . Exploring in Yahoo I at last stumbled upon this site. Reading this information So i am happy to convey that I have a very good uncanny feeling I discovered just what I needed. I most certainly will make certain to do not forget this website and give it a glance on a constant basis.

  27. Howdy would you mind sharing which blog platform you’re using? I’m going to start my own blog soon but I’m having a tough time making a decision between BlogEngine/Wordpress/B2evolution and Drupal. The reason I ask is because your design seems different then most blogs and I’m looking for something unique. P.S Apologies for getting off-topic but I had to ask!

  28. Thanks for the suggestions you talk about through this web site. In addition, quite a few young women who seem to become pregnant don’t even try and get health insurance because they are full of fearfulness they couldn’t qualify. Although some states at this moment require that insurers supply coverage irrespective of the pre-existing conditions. Premiums on all these guaranteed programs are usually greater, but when thinking about the high cost of medical care it may be your safer approach to take to protect your current financial future.

  29. Robertfap表示:

    https://pharmafst.com/# pharmacie en ligne pas cher

  30. Peterclada表示:

    Pharmacie en ligne livraison Europe Livraison rapide pharmacie en ligne pas cher pharmafst.shop

發佈留言

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