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

27,715 Responses

  1. U888表示:

    Hello there! I know this is kind of off topic but I was wondering which blog platform are you using for this site? I’m getting sick and tired of WordPress because I’ve had problems with hackers and I’m looking at alternatives for another platform. I would be fantastic if you could point me in the direction of a good platform.

  2. WW88表示:

    Right now it sounds like Movable Type is the top blogging platform available right now. (from what I’ve read) Is that what you are using on your blog?

  3. WilsonVah表示:

    pharmacie en ligne fiable: Cialis sans ordonnance 24h – pharmacie en ligne france livraison belgique

  4. Vftjhgdbntzef表示:

    100 фриспинов за регистрацию и множество бонусов для регулярных игроков. Clubnika casino открыла свой телеграм канал. Ищи нас по ID @clubnika_casino_site или переходи по ссыле: LINK here Clubnika Casino сайт

  5. Hi88表示:

    One more thing. I think that there are lots of travel insurance web pages of trustworthy companies that permit you to enter your holiday details and find you the rates. You can also purchase this international travel cover policy on internet by using the credit card. All that you should do is to enter your current travel specifics and you can see the plans side-by-side. Just find the package that suits your financial budget and needs and then use your credit card to buy that. Travel insurance on the web is a good way to begin looking for a respected company for international holiday insurance. Thanks for giving your ideas.

  6. WW88表示:

    I’ve come across that nowadays, more and more people will be attracted to video cameras and the field of pictures. However, being photographer, you must first shell out so much time deciding the exact model of dslr camera to buy and moving store to store just so you could buy the least expensive camera of the brand you have decided to choose. But it won’t end at this time there. You also have take into consideration whether you can purchase a digital dslr camera extended warranty. Thanks a bunch for the good guidelines I acquired from your site.

  7. Hi88表示:

    Thanks for another great article. Where else could anybody get that kind of information in such a perfect way of writing? I have a presentation next week, and I am on the look for such info.

  8. WW88表示:

    It’s the best time to make some plans for the long run and it’s time to be happy. I’ve learn this put up and if I could I wish to recommend you few fascinating issues or suggestions. Maybe you could write subsequent articles referring to this article. I wish to learn even more issues about it!

  9. WW88表示:

    Admiring the dedication you put into your website and detailed information you offer. It’s good to come across a blog every once in a while that isn’t the same old rehashed information. Wonderful read! I’ve saved your site and I’m including your RSS feeds to my Google account.

  10. U888表示:

    Thanks for the auspicious writeup. It in truth was once a entertainment account it. Look advanced to far brought agreeable from you! By the way, how could we keep in touch?

  11. WW88表示:

    Thanks for the advice on credit repair on this site. The things i would tell people should be to give up the actual mentality that they can buy right now and pay back later. As being a society we all tend to make this happen for many factors. This includes getaways, furniture, plus items we want. However, you should separate your current wants out of the needs. When you are working to improve your credit score you really have to make some sacrifices. For example you possibly can shop online to economize or you can check out second hand merchants instead of high-priced department stores with regard to clothing.

  12. U888表示:

    Something more important is that when evaluating a good internet electronics retail outlet, look for online stores that are consistently updated, always keeping up-to-date with the newest products, the perfect deals, and also helpful information on services. This will ensure you are doing business with a shop that stays on top of the competition and offers you things to make intelligent, well-informed electronics buys. Thanks for the essential tips I’ve learned from the blog.

  13. NorbertKep表示:

    Viagra homme prix en pharmacie sans ordonnance: Viagra pharmacie – SildГ©nafil 100mg pharmacie en ligne

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

  15. Hi88表示:

    Hiya very cool blog!! Guy .. Excellent .. Wonderful .. I will bookmark your site and take the feeds also?I’m happy to search out numerous helpful info here within the publish, we need develop extra techniques on this regard, thank you for sharing. . . . . .

  16. Hi88表示:

    Thanks for discussing your ideas in this article. The other thing is that each time a problem arises with a pc motherboard, people should not take the risk connected with repairing this themselves because if it is not done right it can lead to irreparable damage to the full laptop. In most cases, it is safe just to approach your dealer of a laptop for any repair of that motherboard. They’ve already technicians who have an knowledge in dealing with mobile computer motherboard challenges and can have the right prognosis and execute repairs.

  17. U888表示:

    Thanks a lot for sharing this with all folks you actually understand what you’re speaking about! Bookmarked. Please additionally talk over with my web site =). We could have a link change agreement among us!

  18. 789bet表示:

    certainly like your website but you need to check the spelling on quite a few of your posts. Many of them are rife with spelling issues and I find it very bothersome to tell the truth nevertheless I will definitely come back again.

  19. WilsonVah表示:

    Viagra femme sans ordonnance 24h: Viagra pharmacie – Viagra sans ordonnance 24h Amazon

  20. Richardprurf表示:

    https://pharmaciemeilleurprix.shop/# pharmacie en ligne pas cher
    pharmacie en ligne france pas cher

  21. Hi88表示:

    I am typically to blogging and i really appreciate your content. The article has actually peaks my interest. I’m going to bookmark your site and maintain checking for brand spanking new information.

  22. 789bet表示:

    Hi there! This is kind of off topic but I need some guidance from an established blog. Is it very hard to set up your own blog? I’m not very techincal but I can figure things out pretty fast. I’m thinking about setting up my own but I’m not sure where to begin. Do you have any tips or suggestions? Cheers

  23. WW88表示:

    I?ve been exploring for a little for any high quality articles or blog posts on this sort of area . Exploring in Yahoo I at last stumbled upon this web site. Reading this info 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 sure to do not forget this website and give it a glance regularly.

  24. Jacobbep表示:

    п»їpharmacie en ligne france https://viagrameilleurprix.shop/# Viagra sans ordonnance livraison 48h

  25. Sayfaya git表示:

    861886 711445This was an incredible post. Really loved studying your site post. Your data was quite informative and valuable. I think you will proceed posting and updating frequently. Looking forward to your subsequent one. 274033

  26. Jacobbep表示:

    Achat mГ©dicament en ligne fiable https://tadalafilmeilleurprix.com/# pharmacies en ligne certifiГ©es

  27. Perryzoozy表示:

    п»їpharmacie en ligne france Tadalafil sans ordonnance en ligne Achat mГ©dicament en ligne fiable

  28. U888表示:

    I loved as much as you will receive carried out right here. The sketch is tasteful, your authored material stylish. nonetheless, you command get bought an nervousness over that you wish be delivering the following. unwell unquestionably come further formerly again as exactly the same nearly a lot often inside case you shield this increase.

  29. WilsonVah表示:

    pharmacies en ligne certifiГ©es: kamagra oral jelly – vente de mГ©dicament en ligne

發佈留言

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