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

  1. You actually make it seem so easy with your presentation but I find this topic to be really something that I think I would never understand. It seems too complex and very broad for me. I’m looking forward for your next post, I will try to get the hang of it!

  2. Hi there, I found your web site via Google while searching for a related topic, your site came up, it looks great. I have bookmarked it in my google bookmarks.

  3. hello!,I like your writing so much! share we communicate more about your article on AOL? I require a specialist on this area to solve my problem. May be that’s you! Looking forward to see you.

  4. DouglasGed表示:

    ed online treatment: ED meds online with insurance – online erectile dysfunction prescription

  5. namii1455表示:

    Hi, Neat post. There is a problem with your site in internet explorer, would check this? IE still is the market leader and a huge portion of people will miss your magnificent writing because of this problem.

  6. DouglasGed表示:

    reputable mexican pharmacies online: Best pharmacy in Mexico – mexican online pharmacies prescription drugs

  7. DouglasGed表示:

    india pharmacy: Online medicine home delivery – pharmacy website india

  8. Eliminate surprises: formal portfolio project oversight provides managers and executives with a process to identify potential problems earlier in the project lifecycle, and the visibility to take corrective action before they impact financial results.

  9. fuji_chan vk表示:

    I would also love to add that if you do not already have got an insurance policy or perhaps you do not take part in any group insurance, you could well benefit from seeking the aid of a health insurance broker. Self-employed or those with medical conditions ordinarily seek the help of the health insurance broker. Thanks for your writing.

  10. vavada_ixSl表示:

    Заработай миллионы в казино Vavada, играй с удовольствием.
    Выбери Vavada и окунись в мир азарта, добивайся больших результатов.
    Ощути азарт и адреналин с Vavada Casino, играй с умом.
    Начни выигрывать уже сегодня в Vavada Casino, начни игру.
    На Vavada ты найдешь самые популярные игры и слоты, испытай свои силы и возможности.
    Попробуй удачу в Vavada и стань богаче, стань победителем.
    Играй в Vavada и получи бонус за первый депозит, начни игру с лучшими условиями.
    Присоединяйся к лидерам и выигрывай в Vavada, стремись к победе.
    vavada com зеркало https://vavadakiev.vavada-casino.com.ua/ .

  11. My brother recommended I would possibly like this blog. He was entirely right. This submit actually made my day. You cann’t consider simply how a lot time I had spent for this info! Thanks!

  12. Thanks for giving your ideas. I would also like to express that video games have been actually evolving. Modern tools and innovative developments have aided create genuine and enjoyable games. These types of entertainment games were not actually sensible when the real concept was being experimented with. Just like other designs of technological know-how, video games as well have had to progress as a result of many many years. This is testimony towards fast growth of video games.

  13. As I web site possessor I believe the content matter here is rattling fantastic , appreciate it for your efforts. You should keep it up forever! Good Luck.

  14. Virtually all of whatever you point out happens to be astonishingly legitimate and it makes me ponder why I hadn’t looked at this with this light previously. This article really did turn the light on for me as far as this specific topic goes. Nonetheless at this time there is actually one particular factor I am not really too comfy with and while I attempt to reconcile that with the actual core theme of your issue, permit me observe just what the rest of the readers have to point out.Very well done.

  15. An interesting discussion is worth comment. I feel that you should write more on this subject, it may not be a taboo subject however typically people are not sufficient to talk on such topics. To the next. Cheers

  16. whoah this blog is great i like reading your posts. Keep up the good paintings! You already know, a lot of persons are hunting around for this info, you could help them greatly.

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

  18. obviously like your website but you need to check the spelling on quite a few of your posts. Several of them are rife with spelling issues and I find it very troublesome to tell the truth nevertheless I will surely come back again.

  19. One thing I’ve noticed is always that there are plenty of misguided beliefs regarding the lenders intentions whenever talking about foreclosure. One myth in particular is the fact the bank desires your house. The financial institution wants your dollars, not the house. They want the funds they gave you together with interest. Staying away from the bank is only going to draw a new foreclosed realization. Thanks for your publication.

  20. lady atom表示:

    I can’t express how much I appreciate the effort the author has put into writing this exceptional piece of content. The clarity of the writing, the depth of analysis, and the wealth of information provided are simply impressive. His passion for the subject is apparent, and it has undoubtedly struck a chord with me. Thank you, author, for offering your wisdom and enlightening our lives with this extraordinary article!

  21. I have observed that car insurance organizations know the cars and trucks which are prone to accidents and other risks. Additionally , they know what form of cars are susceptible to higher risk as well as the higher risk they’ve got the higher a premium fee. Understanding the basic basics associated with car insurance can help you choose the right type of insurance policy that could take care of your wants in case you become involved in an accident. Thank you for sharing your ideas on the blog.

  22. JasonDuece表示:

    Fafabet South Africa
    fafabet only sports betting
    Step into the thrilling universe of Fafabet’s casino, a place pulsating with excitement and brimming with opportunities for big wins! Whether you’re a seasoned gambler or a curious newcomer, this review will guide you through the vibrant selection of top-tier games, enticing bonuses, effective strategies, and seamless mobile play. Get ready to transform your gaming experience and discover why Fafabet is the go-to destination for online casino enthusiasts!
    Best Casino Games at Fafabet
    brings the excitement of a real casino directly to your screen, featuring a curated selection of games that cater to both new and seasoned players. The focus on popular games such as roulette, blackjack, and poker ensures a varied and engaging experience, providing options for strategic play, quick wins, and everything in between. This selection is not just about variety; it’s tailored to enhance player engagement and retention. The inclusion of games with different levels of complexity and reward strategies meets the diverse needs and preferences of the global online gambling community, making Fafabet a top choice for live casino enthusiasts.

    Choose Your Game: Online Roulette, Blackjack, Poker
    The heart of Fafabet’s live casino lies in its comprehensive offering of classic games, which are among the most popular and enduring in the gambling world. Let’s focus on the star of the casino floor: Roulette. This game not only attracts players with its simplicity and elegance but also offers various versions to suit different tastes and betting styles.

  23. I really like your wordpress theme, where did you down load it through?

  24. I do not even know how I ended up here, but I thought this post was good. I don’t know who you are but certainly you are going to a famous blogger if you are not already 😉 Cheers!

  25. Next we’ll turn to a trusted expert for advice on bargains, scams and personal credit: Clark Howard.

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

  27. DouglasGed表示:

    order ed pills: ed pills online – online ed prescription

  28. Diplomi_fcEa表示:

    Здравствуйте!
    Купить документ университета можно у нас.
    arbitrajniki.ru/forums/topic/kuplju-diplomy-v-ekaterinburge-s321b

  29. Hey very cool website!! Man .. Excellent .. Amazing .. I’ll bookmark your blog and take the feeds also?I’m happy to find a lot of useful info here in the post, we need develop more techniques in this regard, thanks for sharing. . . . . .

發佈留言

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