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

  1. Perryzoozy表示:

    pharmacie en ligne avec ordonnance Cialis sans ordonnance 24h Pharmacie sans ordonnance

  2. xmas wall art表示:

    I have read several good stuff here. Definitely worth bookmarking for revisiting. I wonder how much effort you put to create such a great informative site.

  3. Terrific work! This is the type of info that should be shared around the internet. Shame on Google for not positioning this post higher! Come on over and visit my site . Thanks =)

  4. xmas wall art表示:

    Today, I went to the beach with my kids. I found a sea shell and gave it to my 4 year old daughter and said “You can hear the ocean if you put this to your ear.” She placed the shell to her ear and screamed. There was a hermit crab inside and it pinched her ear. She never wants to go back! LoL I know this is completely off topic but I had to tell someone!

  5. Thanks alot : ) for your post. I would like to comment that the tariff of car insurance varies from one scheme to another, simply because there are so many different issues which give rise to the overall cost. For example, the make and model of the vehicle will have a huge bearing on the charge. A reliable aged family automobile will have a more affordable premium than a flashy racecar.

  6. WilsonVah表示:

    п»їpharmacie en ligne france: cialis generique – pharmacie en ligne

  7. WilsonVah表示:

    pharmacie en ligne france fiable: Tadalafil sans ordonnance en ligne – pharmacie en ligne france livraison belgique

  8. Richardprurf表示:

    https://viagrameilleurprix.com/# Viagra homme prix en pharmacie sans ordonnance
    pharmacie en ligne

  9. MatthewsoodE表示:

    Most flights don’t want you joining the Mile-High Club. This company encourages it
    Кракен тор
    In our travel news roundup this week: the rise in solo dining, where to save money at US ski resorts, plus the Californian hot-air balloon company offering a rather cheeky package.

    Your love keeps lifting me higher
    Is it getting hot in here, or is a gas-burner propelling a dirigible above our heads?

    A California-based hot-air balloon company is offering mile-high flights – with amorous Mile-High Club privileges – over the Temecula countryside.

    Guests can enjoy the views with a whole basket to themselves – and a privacy screen separating the pilot compartment from the passenger cabin.

    The pilot, who Magical Adventure Balloon Rides promises will be wearing protective hearing gear and focused solely on flying, ascends the balloon to 5,280 feet (about 1,610 meters), which is about 2,000 feet higher than a typical recreational flight.

    While intimate clinches are usually thoroughly discouraged in the skies, the company invites you to bring your own bedding and music playlist. A complimentary Champagne breakfast is included to fuel your frolics, of whatever sort.

    Pricing for two passengers starts at $1,400. If your mantra is “the more the merrier,” each additional adult in the larger 10-person basket is $159.

    The Mile-High Club flight is just one of a host of packages on offer, from wine tours to company picnics, the rest of which are considerably more family-friendly.
    All by myself
    Sometimes it can seem like the world is full of lovers floating high on cloud nine, but don’t fret if you’re going it alone this Valentine’s season: You’re bang on trend.

    Millennials and Gen Z are breaking down the stigma attached to solo dining in an era when more Americans live alone than ever before. Some do it for convenience; some do it for freedom — either way, reservations for one are on the rise.

    Once you’ve mastered dining alone, it’s time for bigger challenges, such as walking across Saudi Arabia. British explorer Alice Morrison, who has been called “Indiana Jones for girls,” is in the middle of her five-month trek of 2,500 kilometers (about 1,550 miles).

    Others are opting for a permanent adventure. Californian Jason Bennett gave up his life in San Francisco for a new home in Colombia. Today he says his happiness is “off the charts.”

  10. Jacobbep表示:

    pharmacie en ligne france pas cher https://viagrameilleurprix.shop/# Prix du Viagra 100mg en France

  11. WilsonVah表示:

    Pharmacie sans ordonnance: Pharmacies en ligne certifiees – Pharmacie Internationale en ligne

  12. Hello there, You have done a great job. I?ll definitely digg it and in my opinion suggest to my friends. I’m sure they’ll be benefited from this site.

  13. Jacobbep表示:

    pharmacie en ligne https://kamagrameilleurprix.shop/# pharmacie en ligne france livraison internationale

  14. This giant collection of advantageous artwork and antiques had been assembled by the Countess of Westmorland and Lady Georgiana Fane.

  15. This is the precise blog for anybody who wants to seek out out about this topic. You realize a lot its nearly arduous to argue with you (not that I actually would need?HaHa). You definitely put a new spin on a subject thats been written about for years. Great stuff, just great!

  16. I have read some just right stuff here. Definitely worth bookmarking for revisiting. I surprise how much effort you set to create any such excellent informative site.

  17. Richardprurf表示:

    https://viagrameilleurprix.com/# Viagra gГ©nГ©rique sans ordonnance en pharmacie
    pharmacie en ligne avec ordonnance

  18. Wonderful blog! I found it while browsing 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! Many thanks

  19. Perryzoozy表示:

    Pharmacie sans ordonnance achat kamagra pharmacies en ligne certifiГ©es

  20. I adore your wp web template, exactly where do you download it from?

  21. These glassmaking methods may have been transmitted from cultures in Western Asia.

  22. Richardprurf表示:

    https://tadalafilmeilleurprix.shop/# pharmacie en ligne avec ordonnance
    pharmacies en ligne certifiГ©es

  23. NorbertKep表示:

    SildГ©nafil Teva 100 mg acheter: viagra sans ordonnance – Le gГ©nГ©rique de Viagra

  24. Dustinaccex表示:

    Lucky Jet – твой шанс на большие выигрыши!
    Попробуй захватывающую краш-игру прямо сейчас! Регистрируйся и получи бонус до 500% на первый депозит с промокодом: LuckyJetTeam.
    лаки джет играть
    Об игре
    Lucky Jet — это не просто игра, а захватывающее приключение, в котором каждый момент может стать решающим! Эта краш-игра бросает вызов вашим инстинктам и способности быстро принимать решения. В основе игры — динамичная механика, где игроки ставят на рост коэффициента, но задача не в том, чтобы ждать до последнего, а вовремя вывести свой выигрыш, прежде чем персонаж взлетит слишком высоко и случится крах.

    Чем выше коэффициент, тем более значительная награда! Но не забывайте: в этом азартном путешествии важен каждый момент, ведь именно ваше решение о выводе решит, насколько велик будет ваш выигрыш. Это не просто игра, а настоящее испытание на скорость и удачу! Простые правила, быстрые раунды и реальные выигрыши – вот почему игроки выбирают Lucky Jet.

    Бонусы и промокоды в Lucky Jet
    В Lucky Jet вас ждут щедрые бонусы и эксклюзивные промокоды, которые помогут увеличить ваш баланс и продлить удовольствие от игры! Мы ценим активных игроков и регулярно запускаем новые акции, чтобы сделать ваш игровой процесс еще выгоднее.

    Актуальные бонусные предложения
    Бонус 500% на первый депозит
    Используйте промокод LuckyJetTeam при пополнении счета и получите увеличение депозита в 5 раз! Это отличная возможность начать игру с солидным запасом.
    Еженедельные акции и фриспины
    Чем больше вы играете, тем больше подарков получаете! Участвуйте в регулярных промо-акциях и получайте фриспины, бонусные деньги и дополнительные награды за активность.
    Кэшбэк до 10%
    Проиграли? Не беда! В Lucky Jet вы можете вернуть часть потерянных средств благодаря системе кэшбэка. Еженедельно вам будет начисляться до 10% возврата от проигранных ставок.
    Следите за новыми акциями! Мы постоянно обновляем бонусные предложения, поэтому не упустите возможность воспользоваться самыми выгодными промо. Подписывайтесь на новости и следите за актуальными акциями, чтобы всегда быть в выигрыше!

    Используйте бонусы и повышайте свои шансы на победу в Lucky Jet!

    Как начать играть в Lucky Jet
    Готовы испытать удачу и выиграть по-крупному? Следуйте этим простым шагам:

    Зарегистрируйтесь на официальном сайте 1win. Процесс регистрации занимает всего пару минут.
    Пополните счет удобным для вас способом: банковской картой, электронными кошельками или даже криптовалютой.
    Откройте Lucky Jet в разделе казино и приготовьтесь к динамичному игровому процессу.
    Сделайте ставку и следите за ростом коэффициента. Чем выше он поднимается – тем больше ваш потенциальный выигрыш.
    Выведите выигрыш до того, как Lucky Jet взлетит! Главное – не жадничать и вовремя остановиться, иначе ставка сгорит.
    Используйте стратегии, анализируйте предыдущие раунды и комбинируйте ставки, чтобы увеличить свои шансы на победу!

  25. Richardprurf表示:

    https://viagrameilleurprix.com/# Viagra 100 mg sans ordonnance
    pharmacie en ligne sans ordonnance

  26. NorbertKep表示:

    pharmacie en ligne france livraison belgique: pharmacie en ligne france – Pharmacie sans ordonnance

  27. Michaelnen表示:

    Most flights don’t want you joining the Mile-High Club. This company encourages it
    kraken darknet
    In our travel news roundup this week: the rise in solo dining, where to save money at US ski resorts, plus the Californian hot-air balloon company offering a rather cheeky package.

    Your love keeps lifting me higher
    Is it getting hot in here, or is a gas-burner propelling a dirigible above our heads?

    A California-based hot-air balloon company is offering mile-high flights – with amorous Mile-High Club privileges – over the Temecula countryside.

    Guests can enjoy the views with a whole basket to themselves – and a privacy screen separating the pilot compartment from the passenger cabin.

    The pilot, who Magical Adventure Balloon Rides promises will be wearing protective hearing gear and focused solely on flying, ascends the balloon to 5,280 feet (about 1,610 meters), which is about 2,000 feet higher than a typical recreational flight.

    While intimate clinches are usually thoroughly discouraged in the skies, the company invites you to bring your own bedding and music playlist. A complimentary Champagne breakfast is included to fuel your frolics, of whatever sort.

    Pricing for two passengers starts at $1,400. If your mantra is “the more the merrier,” each additional adult in the larger 10-person basket is $159.

    The Mile-High Club flight is just one of a host of packages on offer, from wine tours to company picnics, the rest of which are considerably more family-friendly.
    All by myself
    Sometimes it can seem like the world is full of lovers floating high on cloud nine, but don’t fret if you’re going it alone this Valentine’s season: You’re bang on trend.

    Millennials and Gen Z are breaking down the stigma attached to solo dining in an era when more Americans live alone than ever before. Some do it for convenience; some do it for freedom — either way, reservations for one are on the rise.

    Once you’ve mastered dining alone, it’s time for bigger challenges, such as walking across Saudi Arabia. British explorer Alice Morrison, who has been called “Indiana Jones for girls,” is in the middle of her five-month trek of 2,500 kilometers (about 1,550 miles).

    Others are opting for a permanent adventure. Californian Jason Bennett gave up his life in San Francisco for a new home in Colombia. Today he says his happiness is “off the charts.”

  28. あご 漢字表示:

    De QUEEN, Ark.–Lawrence Jesse Haynes Jr., 74, of Hatfield, Ark., died Sunday, Oct.

  29. Haroldsinty表示:

    Most flights don’t want you joining the Mile-High Club. This company encourages it
    kraken onion
    In our travel news roundup this week: the rise in solo dining, where to save money at US ski resorts, plus the Californian hot-air balloon company offering a rather cheeky package.

    Your love keeps lifting me higher
    Is it getting hot in here, or is a gas-burner propelling a dirigible above our heads?

    A California-based hot-air balloon company is offering mile-high flights – with amorous Mile-High Club privileges – over the Temecula countryside.

    Guests can enjoy the views with a whole basket to themselves – and a privacy screen separating the pilot compartment from the passenger cabin.

    The pilot, who Magical Adventure Balloon Rides promises will be wearing protective hearing gear and focused solely on flying, ascends the balloon to 5,280 feet (about 1,610 meters), which is about 2,000 feet higher than a typical recreational flight.

    While intimate clinches are usually thoroughly discouraged in the skies, the company invites you to bring your own bedding and music playlist. A complimentary Champagne breakfast is included to fuel your frolics, of whatever sort.

    Pricing for two passengers starts at $1,400. If your mantra is “the more the merrier,” each additional adult in the larger 10-person basket is $159.

    The Mile-High Club flight is just one of a host of packages on offer, from wine tours to company picnics, the rest of which are considerably more family-friendly.
    All by myself
    Sometimes it can seem like the world is full of lovers floating high on cloud nine, but don’t fret if you’re going it alone this Valentine’s season: You’re bang on trend.

    Millennials and Gen Z are breaking down the stigma attached to solo dining in an era when more Americans live alone than ever before. Some do it for convenience; some do it for freedom — either way, reservations for one are on the rise.

    Once you’ve mastered dining alone, it’s time for bigger challenges, such as walking across Saudi Arabia. British explorer Alice Morrison, who has been called “Indiana Jones for girls,” is in the middle of her five-month trek of 2,500 kilometers (about 1,550 miles).

    Others are opting for a permanent adventure. Californian Jason Bennett gave up his life in San Francisco for a new home in Colombia. Today he says his happiness is “off the charts.”

  30. Jacobbep表示:

    pharmacie en ligne avec ordonnance https://tadalafilmeilleurprix.shop/# pharmacie en ligne

發佈留言

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