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

11,215 Responses

  1. I savour, lead to I discovered exactly what I was looking for. You’ve ended my four day long hunt! God Bless you man. Have a nice day. Bye

  2. Thanks for your suggestions. One thing I’ve noticed is the fact that banks along with financial institutions know the spending behaviors of consumers plus understand that a lot of people max out and about their cards around the holidays. They correctly take advantage of that fact and commence flooding a person’s inbox and also snail-mail box having hundreds of no-interest APR credit cards offers immediately after the holiday season concludes. Knowing that when you are like 98 in the American general public, you’ll hop at the one opportunity to consolidate financial debt and transfer balances to 0 interest rates credit cards.

  3. xxx av 2023表示:

    I?ve learn a few just right stuff here. Definitely worth bookmarking for revisiting. I surprise how much effort you set to make this kind of fantastic informative site.

  4. Предлагаем качественную печать на одежде для любого случая.

  5. Excellent goods from you, man. I’ve understand your stuff previous to and you’re just too great. I really like what you have acquired here, really like what you are stating and the way in which you say it. You make it enjoyable and you still care for to keep it wise. I cant wait to read far more from you. This is really a wonderful website.

  6. bb表示:

    Thanks for your tips on this blog. 1 thing I would wish to say is the fact purchasing consumer electronics items from the Internet is certainly not new. In fact, in the past few years alone, the market for online gadgets has grown considerably. Today, you will find practically any type of electronic device and tools on the Internet, which include cameras in addition to camcorders to computer components and gaming consoles.

  7. I’m impressed by the quality of this content! The author has clearly put a tremendous amount of effort into researching and arranging the information. It’s inspiring to come across an article that not only provides helpful information but also keeps the readers engaged from start to finish. Hats off to her for making such a remarkable piece!

  8. I additionally believe that mesothelioma cancer is a exceptional form of cancers that is commonly found in people previously familiar with asbestos. Cancerous tissues form inside mesothelium, which is a defensive lining which covers almost all of the body’s areas. These cells normally form while in the lining on the lungs, stomach, or the sac which actually encircles the heart. Thanks for discussing your ideas.

  9. Trefrho表示:

    Привет, друзья!
    Легальные способы покупки диплома о среднем полном образовании
    vremya-rasvivat.blogspot.com/2013/03/Mogut-li-novorozhdennye-polzat
    Рады оказаться полезными!.

  10. Uazrinj表示:

    Привет,друзья!
    Купить диплом о высшем образовании.
    telegra.ph/kupit-diplom-ehlektrika-08-13-9

  11. Mazrcro表示:

    Добрый день!
    Легальная покупка диплома ПТУ с сокращенной программой обучения
    bensbookmarks.com/cisco-certified-network-associate-security-ccna.htm

  12. One more thing. In my opinion that there are a lot of travel insurance web sites of dependable companies that allow you to enter a trip details and acquire you the quotes. You can also purchase the actual international travel cover policy on the web by using your own credit card. All you should do would be to enter your own travel particulars and you can start to see the plans side-by-side. You only need to find the plan that suits your finances and needs and after that use your bank credit card to buy that. Travel insurance on the web is a good way to take a look for a respectable company pertaining to international travel insurance. Thanks for giving your ideas.

  13. Jariorgxb表示:

    Добрый день!
    Заказать диплом о высшем образовании
    telegra.ph/diplom-napisat-kupit-08-13-5

  14. Thanks for the good writeup. It in truth used to be a leisure account it. Look complex to more delivered agreeable from you! By the way, how can we be in contact?

  15. Online poker表示:

    Feel free to visit my site; Online poker

  16. Отличный сайт! Всем рекомендую!Лечение наркомании в Киеве

  17. Have a look at my site :: High Stack Poker

  18. MichaelBaste表示:

    https://sport.ua/betting/bookmakers/1xbet/promokod – 14 летние девушки порно

  19. Generally I do not read post on blogs, but I would like to say that this write-up very forced me to try and do so! Your writing style has been surprised me. Thanks, very nice post.

  20. Hi, Neat post. There’s an issue together with your website in internet explorer, might check this? IE nonetheless is the market chief and a huge section of folks will omit your excellent writing because of this problem.

  21. I have learned quite a few important things as a result of your post. I’d also like to mention that there will be a situation where you will have a loan and never need a cosigner such as a Fed Student Support Loan. But when you are getting a loan through a traditional bank then you need to be able to have a co-signer ready to make it easier for you. The lenders will base their very own decision on a few aspects but the most important will be your credit standing. There are some lenders that will also look at your job history and make a decision based on that but in almost all cases it will be based on on your scores.

  22. Reent表示:

    Please provide values below to convert BTC to USD , or vice versa. When the cryptocurrency was launched at the beginning of 2009, as Satoshi Nakamoto mined the bitcoin genesis block (the first-ever block on the Bitcoin blockchain), 50 BTC entered circulation at a price of $0.00. The current market capitalization of BTC is 1,124,064,814,596.61 USD. This value represents the total market value of all coins in circulation, calculated by multiplying the current price of coin by the number of coins in circulation. Create a chart for any currency pair in the world to see their currency history. These currency charts use live mid-market rates, are easy to use, and are very reliable. 1. Choose the relevant cryptocurrency (ETH, BTC, etc.) This field is optional — you can simply enter the Buy and Sell Price.
    https://chillspot1.com/user/culpcylonew1970
    SafeMoon has integrated interoperability into its token, allowing users to bridge their tokens across the Binance Smart Chain, Ethereum, and Polygon. Which means that holders of the SafeMoon Token can now seamlessly transfer their tokens between these blockchain networks. 9. Now we have Binance Smart Chain compatibility with MetaMask, we’re going to add SafeMoon functionality. At the bottom of the main screen click “Add Tokens” and enter the following in the “Token Address” field: Please try searching our site or start again on our homepage. Today we will look at how and where to purchase SafeMoon from. But before that, there is one thing for you to note. Cryptocurrencies are highly volatile assets and it is always advised to do your research before buying them. Most importantly, only invest money that you can afford to lose. 

  23. My page find sex near me (image.google.sh)

  24. You made some decent points there. I appeared on the web for the difficulty and found most people will go together with together with your website.

  25. jimlive vk表示:

    I would like to thnkx for the efforts you have put in writing this site. I’m hoping the same high-grade web site post from you in the upcoming as well. In fact your creative writing abilities has encouraged me to get my own website now. Actually the blogging is spreading its wings quickly. Your write up is a good example of it.

  26. Lazrtoz表示:

    Привет!
    Мы изготавливаем дипломы психологов, юристов, экономистов и прочих профессий по приятным тарифам.
    telegra.ph/novye-standarty-obucheniya-v-medicinskih-vuzah-08-02

  27. plintus_ddKr表示:

    Как выбрать идеальный плинтус для пола, которые вы обязательно должны знать.
    Какой цвет плинтуса выбрать для гармонии в интерьере, подчеркнуть дизайн помещения.
    Шаг за шагом: установка плинтуса, легко и быстро.
    Почему плинтус сверкает в темноте, о которых вы не знали.
    Лучшие материалы для изготовления напольных плинтусов, который важно учитывать при покупке.
    Как сделать плинтус необычным элементом декора, которые вдохновят вас на новые решения.
    Как выбрать плинтус для ламината, для создания идеального сочетания цветов.
    Плинтус как элемент безопасности в доме, для предотвращения травм.
    Как сделать плинтус стильным акцентом в интерьере, которые покорят вас своей оригинальностью.
    Основные моменты при выборе плинтуса, для придания завершенности ремонту.
    Необычные идеи дизайна с использованием плинтуса, которые преобразят ваш дом.
    прогулянкова коляска carrello https://kolyaskicarello.ru/ .

  28. unicorn表示:

    I think this is one of the most important info for me. And i’m satisfied studying your article. But wanna statement on some common things, The site style is perfect, the articles is actually great : D. Just right task, cheers

發佈留言

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