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...

23,196 Responses

  1. live sex chat表示:

    Hey there! I just wanted to ask if you ever have any trouble with hackers? My last blog (wordpress) was hacked and I ended up losing many months of hard work due to no backup. Do you have any solutions to protect against hackers?

  2. mzplay表示:

    obviously like your website but you need to check the spelling on several of your posts. Many of them are rife with spelling problems and I find it very bothersome to tell the truth nevertheless I will surely come back again.

  3. JasonUnsoG表示:

    http://slotsiteleri25.com/# slot siteleri

  4. The UCLA Film and television Archive will probably be screening Buster Keaton’s The general, together with dwell organ accompaniment.

  5. Thanks for giving your ideas. The first thing is that college students have an alternative between federal student loan plus a private student loan where it’s easier to select student loan consolidation than through the federal student loan.

  6. Wallacefex表示:

    sweet bonanza demo oyna: sweet bonanza giris – sweet bonanza

  7. The exact definition of economic improvement has been contested: whereas economists within the twentieth century considered growth primarily in terms of financial growth, sociologists instead emphasized broader processes of change and modernization.

  8. BradleyEdino表示:

    deneme bonusu veren siteler yeni deneme bonusu veren siteler denemebonusuverensiteler25

  9. FrankEmine表示:

    sweet bonanza slot: sweet bonanza kazanma saatleri – sweet bonanza yorumlar

  10. In September 2014, Express Computer reported how MobiKwik was partnering with GoDaddy and other international companies to help them comply with Indian payment regulations.

  11. Wallacefex表示:

    sweet bonanza slot: sweet bonanza oyna – sweet bonanza slot

  12. 颅For this reason, many people plan a replacement and redecoration project together.

  13. FrankEmine表示:

    slot oyunlar?: en cok kazand?ran slot oyunlar? – en cok kazand?ran slot oyunlar?

  14. Madie表示:

    Here is my web page … Madie

  15. вывод из запоя круглосуточно ростов http://www.vyvod-iz-zapoya-rostov27.ru/ .

  16. FrankEmine表示:

    canl? casino siteleri: guvenilir casino siteleri – guvenilir casino siteleri

  17. DannyUnded表示:

    How Nigeria’s biggest city became the world’s hottest winter party destination
    casino bonus

    It’s a world of endless parties and sleepless nights. A relentless celebration that turns West Africa – and especially Nigeria’s largest city, Lagos – into one of the hottest destinations on the continent, if not the planet, right in the middle of winter.

    Detty December is a magical time between December and early January when diaspora communities and tourists flock to Ghana, Nigeria and South Africa for an unforgettable experience filled with flavourful food, soulful African music and sunshine.

    Beach parties, festivals and top-tier performances fuel the energy, while fashion takes center stage, with everyone dressing to impress.

    Nearly two-thirds of Nigeria’s population is under 25, according to the United Nations Population Fund, making this one of the world’s youngest countries.

    Internationally renowned Afrobeats performers and foreign artists make surprise appearances. DJs take to the streets, blasting powerful beats from consoles mounted atop bright yellow minibuses.

    At times it’s all-consuming. Good luck getting hair salon appointments, affordable air tickets or navigating Lagos’ already notorious traffic when the party crowds are in town.

    Detty December (“detty” is a playful corruption of “dirty”) is a triumphant celebration of culture, music and good vibes that has evolved in recent years during the traditional holidays influx of diaspora returnees, which heightened in 2018 when Ghana ran a launched a successful “Year of Return” campaign actively encouraging people to visit their ancestral homelands.

    It’s gathered pace over the past five years, gaining an international reputation, as IJGBs (“I Just Got Backs”) and their friends arrive in batches, eager to unwind and blow off steam after the fast-paced, hard-working year they’ve had overseas.

    For many in the vast Nigerian diaspora, it is a deeply personal homecoming, a chance to reconnect with their heritage, traditions and families while immersing themselves in the lively energy of Nigerian life.

  18. JasonUnsoG表示:

    https://slotsiteleri25.com/# az parayla cok kazandiran slot oyunlar?

  19. BradleyEdino表示:

    deneme bonusu veren yeni siteler yeni deneme bonusu veren siteler deneme bonusu veren siteler

  20. This web site doesn’t display appropriately on my iphone – you might wanna try and repair that

  21. Whichever path you choose, remember it’s all about creating your distinctive symphony of words.

  22. In USA, health providers still prefer vial and syringes, which make them a good market for injection pen.

  23. aipc 保険表示:

    There are number of websites on internet world popping up and they are offering attractive things as the competition grows.

  24. The Nationwide Foundation for Debt Management (NFDM) is a non-profit (501(c)(3)) client training organization devoted to educating folks about personal finance, residence possession and money administration.

  25. вывод из запоя ростовская область вывод из запоя ростовская область .

  26. Wallacefex表示:

    en kazancl? slot oyunlar?: az parayla cok kazandiran slot oyunlar? – en kazancl? slot oyunlar?

  27. JasonUnsoG表示:

    http://slotsiteleri25.com/# en kazancl? slot oyunlar?

發佈留言

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