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

  1. Bernardshoor表示:

    Kamagra pharmacie en ligne: Achetez vos kamagra medicaments – kamagra livraison 24h

  2. BradleyJaire表示:

    cialis sans ordonnance: Tadalafil 20 mg prix sans ordonnance – cialis sans ordonnance tadalmed.shop

  3. Bernardshoor表示:

    Cialis generique prix: Pharmacie en ligne Cialis sans ordonnance – Tadalafil 20 mg prix sans ordonnance tadalmed.shop

  4. WilliamNug表示:

    New design revealed for Airbus hydrogen plane
    renzo protocol

    In travel news this week: Bhutan’s spectacular new airport, the world’s first 3D-printed train station has been built in Japan, plus new designs for Airbus’ zero-emission aircraft and France’s next-generation high-speed trains.

    Grand designs
    European aerospace giant Airbus has revealed a new design for its upcoming fully electric, hydrogen-powered ZEROe aircraft. powered by hydrogen fuel cells.

    The single-aisle plane now has four engines, rather than six, each powered by their own fuel cell stack.

    The reworked design comes after the news that the ZEROe will be in our skies later than Airbus hoped.

    The plan was to launch a zero-emission aircraft by 2035, but now the next-generation single-aisle aircraft is slated to enter service in the second half of the 2030s.

    Over in Asia, the Himalayan country of Bhutan is building a gloriously Zen-like new airport befitting a nation with its very own happiness index.

    Gelephu International is designed to serve a brand new “mindfulness city,” planned for southern Bhutan, near its border with India.

    In rail travel, Japan has just built the world’s first 3D-printed train station, which took just two and a half hours to construct, according to The Japan Times. That’s even shorter than the whizzy six hours it was projected to take.

    France’s high-speed TGV rail service has revealed its next generation of trains, which will be capable of reaching speeds of up to 320 kilometers an hour (nearly 200 mph).

    The stylish interiors have been causing a stir online, as has the double-decker dining car.

    Finally, work is underway in London on turning a mile-long series of secret World War II tunnels under a tube station into a major new tourist attraction. CNN took a look inside.

  5. Peterclada表示:

    Achetez vos kamagra medicaments Achetez vos kamagra medicaments kamagra en ligne

  6. BillieLet表示:

    pharmacie en ligne livraison europe: pharmacie en ligne sans ordonnance – vente de mГ©dicament en ligne pharmafst.com

  7. qq88表示:

    I discovered your blog web site on google and test a few of your early posts. Proceed to maintain up the excellent operate. I just extra up your RSS feed to my MSN News Reader. Searching for forward to studying extra from you in a while!?

  8. Peterclada表示:

    pharmacie en ligne france livraison belgique Livraison rapide pharmacie en ligne fiable pharmafst.shop

  9. Jasontep表示:

    Water and life
    stargate finance
    Lightning is a dramatic display of electrical power, but it is also sporadic and unpredictable. Even on a volatile Earth billions of years ago, lightning may have been too infrequent to produce amino acids in quantities sufficient for life — a fact that has cast doubt on such theories in the past, Zare said.

    Water spray, however, would have been more common than lightning. A more likely scenario is that mist-generated microlightning constantly zapped amino acids into existence from pools and puddles, where the molecules could accumulate and form more complex molecules, eventually leading to the evolution of life.

    “Microdischarges between obviously charged water microdroplets make all the organic molecules observed previously in the Miller-Urey experiment,” Zare said. “We propose that this is a new mechanism for the prebiotic synthesis of molecules that constitute the building blocks of life.”

    However, even with the new findings about microlightning, questions remain about life’s origins, he added. While some scientists support the notion of electrically charged beginnings for life’s earliest building blocks, an alternative abiogenesis hypothesis proposes that Earth’s first amino acids were cooked up around hydrothermal vents on the seafloor, produced by a combination of seawater, hydrogen-rich fluids and extreme pressure.

    Researchers identified salt minerals in the Bennu samples that were deposited as a result of brine evaporation from the asteroid’s parent body. In particular, they found a number of sodium salts, such as the needles of hydrated sodium carbonate highlighted in purple in this false-colored image – salts that could easily have been compromised if the samples had been exposed to water in Earth’s atmosphere.

    Related article
    Yet another hypothesis suggests that organic molecules didn’t originate on Earth at all. Rather, they formed in space and were carried here by comets or fragments of asteroids, a process known as panspermia.

    “We still don’t know the answer to this question,” Zare said. “But I think we’re closer to understanding something more about what could have happened.”

    Though the details of life’s origins on Earth may never be fully explained, “this study provides another avenue for the formation of molecules crucial to the origin of life,” Williams said. “Water is a ubiquitous aspect of our world, giving rise to the moniker ‘Blue Marble’ to describe the Earth from space. Perhaps the falling of water, the most crucial element that sustains us, also played a greater role in the origin of life on Earth than we previously recognized.”

  10. BillieLet表示:

    achat kamagra: kamagra pas cher – Kamagra Oral Jelly pas cher

  11. BradleyJaire表示:

    kamagra en ligne: acheter kamagra site fiable – kamagra livraison 24h

  12. Bernardshoor表示:

    achat kamagra: kamagra livraison 24h – Achetez vos kamagra medicaments

  13. Bernardshoor表示:

    acheter kamagra site fiable: achat kamagra – achat kamagra

  14. Управление домом одним нажатием с Somfy
    Автоматика Somfy Автоматика Somfy . Прокарниз

  15. Bernardshoor表示:

    pharmacie en ligne france pas cher: Livraison rapide – pharmacies en ligne certifiГ©es pharmafst.com

  16. BradleyJaire表示:

    Kamagra Oral Jelly pas cher: kamagra en ligne – kamagra oral jelly

  17. BradleyJaire表示:

    kamagra gel: kamagra pas cher – Acheter Kamagra site fiable

  18. sodo66表示:

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

  19. sodo66表示:

    We are a bunch of volunteers and opening a brand new scheme in our community. Your website offered us with useful info to paintings on. You have performed an impressive activity and our entire community might be thankful to you.

  20. BillieLet表示:

    trouver un mГ©dicament en pharmacie: Livraison rapide – pharmacie en ligne france livraison belgique pharmafst.com

  21. BradleyJaire表示:

    kamagra en ligne: Achetez vos kamagra medicaments – Kamagra Commander maintenant

  22. qq88表示:

    great points altogether, you just won a brand new reader. What might you recommend about your put up that you just made a few days ago? Any certain?

  23. KennethTwisa表示:

    Challenging our perceptions of ‘perfection’
    traderjoexyz exchange
    With health influencers raising the bar for success, the wellness space now often feels like a performative space where people strive to showcase peak physical and mental strength.

    While seeing others’ achievements can be motivating, it can also be discouraging if your progress doesn’t match theirs.

    Each person is chasing the perfect version of themselves — whether it’s a body or a lifestyle — which is dangerous because this is typically an impossible or dangerous version to achieve, Curran said. He added that this type of comparison creates a dangerous cycle in which people constantly feel dissatisfied with their own progress.

    “It’s a fantasy in many ways, and once you start chasing after it, you constantly find yourself embroiled in a sense of doubt and deficit,” he said.

    Curran also noted that wellness challenges can be particularly damaging for women who struggle with perfectionism, as they tend to be bombarded with impossible beauty standards and societal expectations.

    Renee McGregor, a UK-based dietitian who specializes in eating disorders and athlete performance, encourages people to approach wellness trends with curiosity and skepticism. That’s because some influencers and celebrities could be promoting products because there’s a financial benefit for them.

    “The thing to ask yourself about the person you’re taking advice from is what do they gain from it?” McGregor said. “If they are going to gain financially, then you know that they (could be willing) to sell you a lie.”
    Whether you want to try a new challenge or product that promises amazing results, McGregor suggests doing your research and seeking diverse perspectives, including consulting with doctors when possible.

  24. Robertfap表示:

    http://pharmafst.com/# Achat mГ©dicament en ligne fiable

  25. Peterclada表示:

    achat kamagra achat kamagra kamagra en ligne

  26. 58win表示:

    I am extremely inspired together with your writing talents and also with the layout for your weblog. Is this a paid subject matter or did you modify it your self? Anyway keep up the excellent high quality writing, it?s uncommon to peer a great blog like this one these days..

  27. Bernardshoor表示:

    Acheter Viagra Cialis sans ordonnance: Acheter Cialis 20 mg pas cher – Acheter Cialis 20 mg pas cher tadalmed.shop

  28. Jamesacids表示:

    Wellness perfectionism doesn’t exist. Focus on these sustainable habits
    sushiswap exchange
    ou’re scrolling through your phone when you stumble upon the next viral trend: an influencer claiming that following their incredibly strict diet will help you achieve their jaw-dropping physique. Or you see a fresh-faced runner swearing you can run a marathon without any training — just like they did.

    Whether or not you’re actively searching for wellness advice, it’s nearly impossible to avoid hearing about the latest health craze making bold guarantees of transformation.

    As you wonder if these claims hold any truth, you might also question why people often feel motivated to dive into intense challenges — when seemingly simple habits, such as getting enough sleep or eating more vegetables, often feel much harder to tackle.

    Many of us are drawn to these extreme challenges because we’re craving radical change, hoping it will help prove something to ourselves or to others, experts say.

    “We always see these kinds of challenges as opportunities for growth, particularly if we’re in a phase of our life where we’ve let ourselves go,” said Dr. Thomas Curran, associate professor of psychology at the London School of Economics and Political Science and an expert on perfectionism. “Maybe we feel that we need to be healthier, or we just had a breakup or (major) life event.”
    With social media amplifying these movements, it’s easy to see why people are increasingly drawn to the idea of achieving the “perfect” version of themselves. But before jumping into a new wellness challenge, it’s important to take a moment, reflect on your goals, and consider where you’re starting from.

  29. Robertfap表示:

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

  30. sodo66表示:

    Thanks for your posting. One other thing is that if you are marketing your property on your own, one of the challenges you need to be mindful of upfront is just how to deal with property inspection records. As a FSBO retailer, the key concerning successfully shifting your property and saving money on real estate agent commissions is understanding. The more you already know, the more stable your home sales effort will probably be. One area in which this is particularly critical is home inspections.

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

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