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

  1. Thanks for the strategies presented. One thing I additionally believe is that often credit cards featuring a 0 monthly interest often appeal to consumers with zero rate of interest, instant approval and easy internet balance transfers, nonetheless beware of the number one factor that is going to void that 0 easy street annual percentage rate and also throw one out into the poor house rapidly.

  2. Fermin Tille表示:

    You should participate in a contest for among the best blogs on the web. I’ll advocate this web site!

  3. Victorprima表示:

    Their international health workshops are invaluable.
    where to buy generic clomid without prescription
    Their vaccination services are quick and easy.

  4. I was recommended this website by my cousin. I’m not sure whether this post is written by him as nobody else know such detailed about my trouble. You are amazing! Thanks!

  5. WalterCherm表示:

    They provide international health solutions at my doorstep.
    https://cipropharm24.top/
    An unmatched titan in the world of international pharmacies.

  6. Victorprima表示:

    They always offer alternatives and suggestions.
    cheap clomid without rx
    earch our drug database.

  7. What i do not realize is actually how you’re not really much more well-liked than you may be now. You are very intelligent. You realize thus significantly 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 outstanding. Always maintain it up!

  8. What?s Going down i am new to this, I stumbled upon this I have found It absolutely useful and it has aided me out loads. I’m hoping to give a contribution & help different customers like its helped me. Great job.

  9. Wow that was unusual. I just wrote an extremely long comment but after I clicked submit my comment didn’t appear. Grrrr… well I’m not writing all that over again. Anyways, just wanted to say great blog!

  10. WalterCherm表示:

    They keep a broad spectrum of rare medications.
    https://gabapentinpharm24.top/
    Pioneers in the realm of global pharmacy.

  11. Victorprima表示:

    Their patient care is unparalleled.
    where can i get cheap lisinopril without a prescription
    The drive-thru option is a lifesaver.

  12. You can definitely see your enthusiasm in the paintings you write. The sector hopes for even more passionate writers like you who are not afraid to mention how they believe. All the time follow your heart.

  13. kovry_wvEi表示:

    Ковры для уюта вашего дома, откройте.
    Лучшие варианты ковров для вашего дома, приобретите.
    Эко-дизайн: ковры из натуральных материалов, эксклюзивные модели.
    Декорируйте пространство с помощью ковров, уют.
    Безопасные и яркие ковры для детской, разнообразие.
    Традиционные и современные ковры, выберите.
    Создание комфортного рабочего пространства с коврами, уникальность.
    Неприхотливые ковры для занятых людей, узнайте.
    Советы по выбору ковра, читайте.
    Теплота и уют с коврами, подберите.
    Модные ковры 2025 года, освежите.
    Создайте уют на даче с коврами, найдите.
    Как сделать ваш интерьер уникальным с коврами, дизайнерские решения.
    Ковры: от классики до модерна, мир ковров.
    Создайте атмосферу уюта в спальне, мягкие текстуры.
    Качество и стиль от лучших производителей, инвестируйте.
    Ковры для любителей животных, узнайте.
    Ковры, которые сохраняют тепло, стиль.
    Как использовать ковры для зонирования, узнайте.
    маленькие ковры https://kovry-v-moskve.ru/ .

  14. Brooks Kuzyk表示:

    Howdy! This post could not be written any better! Reading through this post reminds me of my old room mate! He always kept chatting about this. I will forward this write-up to him. Pretty sure he will have a good read. Many thanks for sharing!

  15. Jasonzitte表示:

    The team always ensures that I understand my medication fully.
    clomid online
    They offer invaluable advice on health maintenance.

  16. Jasonzitte表示:

    A reliable pharmacy that connects patients globally.
    where can i buy cheap lisinopril pills
    Their commitment to international standards is evident.

  17. Tam Secky表示:

    I believe that avoiding highly processed foods is a first step so that you can lose weight. They can taste fine, but highly processed foods include very little vitamins and minerals, making you eat more simply to have enough strength to get throughout the day. For anyone who is constantly feeding on these foods, switching to cereals and other complex carbohydrates will make you to have more electricity while taking in less. Good blog post.

  18. Danny Curimao表示:

    You actually make it appear really easy with your presentation but I to find this topic to be really one thing that I think I would never understand. It sort of feels too complex and very huge for me. I’m taking a look ahead for your subsequent publish, I will try to get the grasp of it!

  19. Good ? I should certainly pronounce, impressed with your web site. I had no trouble navigating through all the tabs and related information ended up being truly easy to do to access. I recently found what I hoped for before you know it in the least. Reasonably unusual. Is likely to appreciate it for those who add forums or something, web site theme . a tones way for your customer to communicate. Excellent task..

  20. Boy rapists表示:

    Hello my friend! I wish to say that this post is awesome, nice written and include approximately all significant infos. I?d like to see more posts like this.

  21. A psychological well being provider can supply steering and support, serving to you navigate the challenges of residing with somebody with ASPD.

  22. Youre so cool! I dont suppose Ive learn something like this before. So nice to search out anyone with some authentic ideas on this subject. realy thanks for starting this up. this website is one thing that’s needed on the internet, somebody with somewhat originality. useful job for bringing one thing new to the web!

  23. Anja Zogby表示:

    I’m impressed by the quality of this content! The author has obviously put a tremendous amount of effort into researching and organizing the information. It’s inspiring to come across an article that not only gives helpful information but also keeps the readers hooked from start to finish. Great job to him for producing such a brilliant work!

  24. I do agree with all of the ideas you’ve presented in your post. They’re very convincing and will certainly work. Still, the posts are too short for starters. Could you please extend them a little from next time? Thanks for the post.

  25. Shad Celius表示:

    One other thing I would like to express is that rather than trying to suit all your online degree lessons on days that you end work (considering that people are exhausted when they get home), try to receive most of your instructional classes on the weekends and only a few courses for weekdays, even if it means a little time away from your weekend. This is really good because on the weekends, you will be far more rested and concentrated in school work. Thanks a lot for the different guidelines I have discovered from your site.

  26. WalterCherm表示:

    The ambiance of the pharmacy is calming and pleasant.
    https://lisinoprilpharm24.top/
    Always leaving this place satisfied.

  27. Quinton Kuhs表示:

    Another thing I’ve really noticed is always that for many people, bad credit is the reaction of circumstances past their control. One example is they may are already saddled through an illness and because of this they have substantial bills for collections. It can be due to a employment loss and the inability to go to work. Sometimes breakup can truly send the money in the wrong direction. Thanks sharing your thinking on this blog site.

  28. Thanks for sharing superb informations. Your site is very cool. I am impressed by the details that you have on this site. It reveals how nicely you understand this subject. Bookmarked this website page, will come back for more articles. You, my pal, ROCK! I found simply the info I already searched all over the place and simply could not come across. What an ideal web site.

  29. Randal Barket表示:

    Interesting blog post. Some tips i would like to add is that laptop memory should be purchased when your computer still can’t cope with anything you do along with it. One can set up two good old ram boards with 1GB each, as an illustration, but not certainly one of 1GB and one of 2GB. One should make sure the company’s documentation for the PC to make sure what type of ram is needed.

  30. Scammer表示:

    What i do not realize is if truth be told how you are now not actually a lot more well-preferred than you may be right now. You are very intelligent. You recognize therefore considerably on the subject of this subject, made me personally consider it from numerous numerous angles. Its like women and men don’t seem to be interested except it is one thing to accomplish with Woman gaga! Your personal stuffs great. All the time maintain it up!

發佈回覆給「Jasonzitte」的留言 取消回覆

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