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

16,012 Responses

  1. jkeptlubd表示:

    The model has simulated Wizards vs. Rockets 10,000 times and the results are in. We can tell you that the model is leaning Under, and it’s also generated a point-spread pick that is hitting in well over 60% of simulations. You can only see the pick at SportsLine. You are using an outdated browser that is no longer supported. Please upgrade your browser to improve your experience and security. Teams Looking to bet on this NBA matchup between the Memphis Grizzlies and the Houston Rockets?  I’m fully fading the Brooklyn Nets on the second night of a back-to-back, as the team has covered the spread just one time in its last 11 games. With his uncanny shooting ability, Guard Stephen Curry is always a threat to take over a game. The 36-year-old is still in the top 10 in the league in scoring at 26.4 points per game, hitting 38.9% from 3-point range. He’s upped his production in two games against Houston this season, averaging 28.0 points and 6.0 rebounds while hitting 47.8% of his shots from beyond the arc.
    https://urlscan.io/result/2213900b-5d21-46ef-8117-493c2280e38c/loading
    ………………………………………………………………………………………….. Tips Shop If you are a free subscriber, the number of free tips you will get daily will be limited. We drop up to 10 free games every day with a 100% winning rate. You don’t have to be a paid subscriber before you can start winning with our everyday tips. Your 5k, 10k can go a long way if managed carefully. With our free games for the day, you can flip your 5k into at least 50k when used daily. With this, you can pay for our VIP tips and get an opportunity to win even higher. Make Maximum PROFITS with our Premium Tips!!! Click Here To See Our Offer

  2. I have noticed that over the course of creating a relationship with real estate managers, you’ll be able to get them to understand that, in most real estate contract, a commission rate is paid. Eventually, FSBO sellers really don’t “save” the payment. Rather, they try to win the commission by simply doing a great agent’s job. In doing so, they devote their money and also time to carry out, as best they could, the obligations of an agent. Those responsibilities include revealing the home by means of marketing, delivering the home to willing buyers, developing a sense of buyer urgency in order to prompt an offer, preparing home inspections, taking on qualification checks with the financial institution, supervising maintenance, and aiding the closing of the deal.

  3. BarryDof表示:

    https://rybelsus.shop/# semaglutide online

  4. HaroldBig表示:

    cheapest rybelsus pills: rybelsus coupon – buy semaglutide online

  5. I absolutely love your blog and find almost all of your post’s to be exactly what I’m looking for. Does one offer guest writers to write content for you? I wouldn’t mind creating a post or elaborating on most of the subjects you write in relation to here. Again, awesome web log!

  6. Some tips i have observed in terms of laptop memory is there are specifications such as SDRAM, DDR and the like, that must fit the features of the motherboard. If the computer’s motherboard is fairly current and there are no os issues, updating the storage space literally requires under 1 hour. It’s one of several easiest laptop or computer upgrade techniques one can picture. Thanks for expressing your ideas.

  7. online casino表示:

    It is my belief that mesothelioma is most deadly cancer. It has unusual qualities. The more I look at it the greater I am persuaded it does not behave like a true solid cells cancer. In the event mesothelioma is actually a rogue viral infection, then there is the probability of developing a vaccine plus offering vaccination to asbestos uncovered people who are vulnerable to high risk associated with developing long run asbestos connected malignancies. Thanks for discussing your ideas on this important ailment.

  8. Frankevild表示:

    http://ozempic.art/# ozempic cost

  9. Jeremypag表示:

    semaglutide tablets buy semaglutide online buy semaglutide pills

  10. Fantastic beat ! I would like to apprentice while you amend your website, how can i subscribe for a blog site? The account aided me a acceptable deal. I had been tiny bit acquainted of this your broadcast offered bright clear concept

  11. With havin so much written content do you ever run into any problems of plagorism or copyright violation? My website has a lot of unique content I’ve either written myself or outsourced but it appears a lot of it is popping it up all over the web without my authorization. Do you know any ways to help reduce content from being stolen? I’d definitely appreciate it.

  12. What an insightful and thoroughly-researched article! The author’s attention to detail and capability to present intricate ideas in a digestible manner is truly praiseworthy. I’m totally captivated by the depth of knowledge showcased in this piece. Thank you, author, for offering your wisdom with us. This article has been a game-changer!

  13. I will right away grab your rss as I can not find your e-mail subscription link or e-newsletter service. Do you have any? Kindly let me know in order that I could subscribe. Thanks.

  14. RamonRek表示:

    ozempic generic: ozempic – buy cheap ozempic

  15. lesbian porn表示:

    Someone essentially help to make seriously articles I would state. This is the first time I frequented your web page and thus far? I amazed with the research you made to make this particular publish amazing. Great job!

  16. Hey very cool web site!! Man .. Beautiful .. Amazing .. I’ll bookmark your website and take the feeds additionally?I am satisfied to find numerous useful info here within the put up, we want work out more strategies on this regard, thank you for sharing. . . . . .

  17. gay porn表示:

    Wonderful blog! Do you have any tips and hints for aspiring writers? I’m hoping to start my own blog soon but I’m a little lost on everything. Would you propose 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? Appreciate it!

  18. HaroldBig表示:

    ozempic online: ozempic coupon – Ozempic without insurance

  19. Профессиональный сервисный центр по ремонту электросамокатов в Москве.
    Мы предлагаем: ремонт электросамокатов
    Наши мастера оперативно устранят неисправности вашего устройства в сервисе или с выездом на дом!

  20. BarryDof表示:

    http://ozempic.art/# ozempic online

  21. Сервисный центр предлагает ремонт телевизоров huawei адреса качественый ремонт телевизора huawei

  22. lesbian porn表示:

    An interesting discussion is value comment. I think that you need to write extra on this matter, it won’t be a taboo subject however generally individuals are not sufficient to talk on such topics. To the next. Cheers

  23. Профессиональный сервисный центр по ремонту сигвеев в Москве.
    Мы предлагаем: сервис сигвей
    Наши мастера оперативно устранят неисправности вашего устройства в сервисе или с выездом на дом!

  24. Nice blog here! Also your website loads up very fast! What web host are you using? Can I get your affiliate link to your host? I wish my site loaded up as fast as yours lol

  25. Профессиональный сервисный центр по ремонту сетевых хранилищ в Москве.
    Мы предлагаем: ремонт сетевых хранилищ в москве
    Наши мастера оперативно устранят неисправности вашего устройства в сервисе или с выездом на дом!

  26. Профессиональный сервисный центр по ремонту планшетов в Москве.
    Мы предлагаем: ремонт планшетов работа
    Наши мастера оперативно устранят неисправности вашего устройства в сервисе или с выездом на дом!

發佈留言

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