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,453 Responses

  1. gary表示:

    I am really enjoying the theme/design of your blog. Do you ever run into any web browser compatibility issues? A few of my blog readers have complained about my blog not working correctly in Explorer but looks great in Opera. Do you have any advice to help fix this problem?

  2. Wonderful blog! I found it while surfing around on Yahoo News. Do you have any suggestions on how to get listed in Yahoo News? I’ve been trying for a while but I never seem to get there! Cheers

  3. Pretty nice post. I just stumbled upon your blog and wanted to say that I’ve really enjoyed surfing around your blog posts. After all I will be subscribing to your rss feed and I hope you write again very soon!

  4. I think this is among the most vital info for me. And i am glad reading your article. But should remark on few general things, The web site style is perfect, the articles is really nice : D. Good job, cheers

  5. Arnoldten表示:

    best online pharmacies in mexico mexico pharmacy mexico pharmacy

  6. Hey there! I know this is kinda off topic but I’d figured I’d ask. Would you be interested in trading links or maybe guest writing a blog post or vice-versa? My blog discusses a lot of the same topics as yours and I feel we could greatly benefit from each other. If you’re interested feel free to send me an e-mail. I look forward to hearing from you! Awesome blog by the way!

  7. I found your weblog site on google and verify a few of your early posts. Proceed to keep up the very good operate. I simply further up your RSS feed to my MSN Information Reader. Seeking forward to studying more from you later on!?

  8. I think this is one of the most vital info for me. And i am glad reading your article. But should remark on some general things, The web site style is ideal, the articles is really excellent : D. Good job, cheers

  9. Lazrscj表示:

    Добрый день!
    Мы изготавливаем дипломы любой профессии по приятным тарифам.
    maliapd.org/plateforme-gt/2024/06/30/купить-диплом-в-люберцах

  10. gary表示:

    It?s actually a great and helpful piece of info. I?m glad that you shared this useful info with us. Please keep us informed like this. Thanks for sharing.

  11. Diplomi_ywEa表示:

    Привет, друзья!
    Купить документ института можно у нас в Москве.
    ast-diplomy.com/kupit-diplom-o-vysshem-obrazovanii

  12. There are definitely a lot of details like that to take into consideration. That could be a nice point to carry up. I provide the ideas above as common inspiration but clearly there are questions just like the one you carry up where a very powerful factor can be working in sincere good faith. I don?t know if greatest practices have emerged round things like that, but I’m sure that your job is clearly identified as a good game. Both boys and girls feel the impression of only a moment?s pleasure, for the rest of their lives.

  13. RichardWrifs表示:

    https://mexicandeliverypharma.com/# mexican online pharmacies prescription drugs

  14. I?ve read a few good stuff here. Definitely worth bookmarking for revisiting. I surprise how much effort you put to create such a magnificent informative website.

  15. our blues表示:

    I’ve been browsing on-line more than three hours nowadays, yet I by no means discovered any interesting article like yours. It?s beautiful price sufficient for me. In my opinion, if all site owners and bloggers made excellent content material as you probably did, the net can be a lot more useful than ever before.

  16. Excellent site you have here but I was wondering if you knew of any forums that cover the same topics talked about here? I’d really like to be a part of group where I can get feed-back from other knowledgeable individuals that share the same interest. If you have any recommendations, please let me know. Thanks!

  17. Heya i?m for the first time here. I came across this board and I in finding It really useful & it helped me out much. I am hoping to provide one thing back and aid others such as you aided me.

  18. Great write-up, I?m regular visitor of one?s site, maintain up the excellent operate, and It is going to be a regular visitor for a lengthy time.

  19. WayneCoirl表示:

    mexican drugstore online: purple pharmacy mexico price list – mexico drug stores pharmacies

  20. DominicJaw表示:

    mexican mail order pharmacies: mexican pharmaceuticals online – mexican online pharmacies prescription drugs

  21. I love your blog.. very nice colors & theme. Did you design this website yourself or did you hire someone to do it for you? Plz reply as I’m looking to design my own blog and would like to find out where u got this from. thank you

  22. audit_djsi表示:

    Надежный аудит для бизнеса в Уфе, для вашей компании.
    Хотите получить качественный аудит в Уфе?, Мы готовы помочь.
    Оптимизация бизнеса с помощью аудита, в свете новых технологий.
    Ваши финансы под контролем с нашим аудитом, узнайте больше.
    Экспертный аудит для вашего бизнеса, позаботьтесь о своем бизнесе.
    Ваш бизнес с нами под защитой, высокое качество услуг.
    Проверка финансов в Уфе, для вашего спокойствия.
    Зачем нужен аудит в Уфе?, не оставайтесь наедине с вопросами.
    Обеспечьте успех вашего бизнеса с нашим аудитом, получите консультацию.
    Аудит, который вы заслуживаете, получите максимум.
    Гарантированный результат аудита, проверенные решения.
    Персонализированный подход к аудиту, получите необходимую поддержку.
    Финансовый аудит для организаций в Уфе, это безопасно.
    Специализированные услуги аудита в Уфе, ваша безопасность — наш приоритет.
    Возможно ли улучшение бизнеса через аудит?, получите ответ у нас.
    Аудит: ваши средства под защитой, просто и надежно.
    Надежные решения для вашего бизнеса, это выгодное решение.
    Получите помощь наших экспертов, обратитесь к профессионалам.
    Обучение по аудиту для начинающих, мы поделимся опытом.
    Как найти идеального аудитора в Уфе?, узнайте больше у нас.
    аудиторские компании аудиторские компании .

  23. Thanks for the ideas you have shared here. Another thing I would like to say is that laptop or computer memory requirements generally go up along with other developments in the technological innovation. For instance, if new generations of processors are introduced to the market, there is certainly usually a similar increase in the shape calls for of both the laptop memory and hard drive room. This is because the program operated through these processor chips will inevitably increase in power to benefit from the new engineering.

  24. Hello, i read your blog from time to time and i own a similar one and i was just curious if you get a lot of spam remarks? If so how do you prevent it, any plugin or anything you can suggest? I get so much lately it’s driving me mad so any assistance is very much appreciated.

  25. What i don’t understood is actually how you’re not actually much more well-liked than you may be right now. You’re very intelligent. You realize thus considerably relating to this subject, made me personally consider it from a lot of varied angles. Its like men and women aren’t fascinated unless it is one thing to do with Lady gaga! Your own stuffs excellent. Always maintain it up!

  26. netflix表示:

    Appreciating the time and effort you put into your website and in depth information you offer. It’s nice to come across a blog every once in a while that isn’t the same outdated rehashed information. Excellent read! I’ve saved your site and I’m including your RSS feeds to my Google account.

  27. twitter表示:

    Hey, I think your blog might be having browser compatibility issues. When I look at your website in Opera, it looks fine but when opening in Internet Explorer, it has some overlapping. I just wanted to give you a quick heads up! Other then that, amazing blog!

  28. Excellent post. I was checking constantly this blog and I am impressed! Very useful information specifically the last part 🙂 I care for such information much. I was looking for this certain information for a long time. Thank you and good luck.

  29. Good day! I know this is kinda off topic however , I’d figured I’d ask. Would you be interested in exchanging links or maybe guest authoring a blog article or vice-versa? My site addresses a lot of the same topics as yours and I believe we could greatly benefit from each other. If you’re interested feel free to shoot me an email. I look forward to hearing from you! Great blog by the way!

  30. Trefoit表示:

    Здравствуйте!
    Как официально купить аттестат 11 класса с упрощенным обучением в Москве
    mipropuestadenegocio.com/category/uncategorized/page/3/
    Рады помочь!.

發佈留言

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