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

  1. Fox表示:

    Hello there! Do you know if they make any plugins to protect against hackers? I’m kinda paranoid about losing everything I’ve worked hard on. Any tips?

  2. DavidCooth表示:

    https://preman69.tech/# Keseruan bermain slot selalu menggoda para pemain

  3. DavidCooth表示:

    http://slotdemo.auction/# Slot dengan tema budaya lokal menarik perhatian

  4. Williecrady表示:

    Banyak pemain menikmati bermain slot secara online http://bonaslot.site/# Slot dengan tema film terkenal menarik banyak perhatian

  5. Williecrady表示:

    Banyak kasino menawarkan permainan langsung yang seru http://slotdemo.auction/# Banyak kasino memiliki promosi untuk slot

  6. ThomasThype表示:

    Mesin slot dapat dimainkan dalam berbagai bahasa: slot 88 – slot88.company

  7. JamesLok表示:

    Slot menawarkan kesenangan yang mudah diakses http://slot88.company/# Mesin slot menawarkan pengalaman bermain yang cepat

  8. website表示:

    I have noticed that in old digital cameras, special receptors help to {focus|concentrate|maintain focus|target|a**** automatically. Those kind of sensors connected with some cams change in contrast, while others make use of a beam involving infra-red (IR) light, particularly in low lighting. Higher standards cameras sometimes use a mix of both systems and will often have Face Priority AF where the video camera can ‘See’ a face and focus only on that. Thank you for sharing your notions on this blog.

  9. hjzgxzpqp表示:

    To participate in the Powerball game, players can purchase a ticket for $2 per play. The game requires players to choose five numbers from one to 69 for the white balls, and one number from one to 26 for the red Powerball. Alternatively, players can opt to receive random numbers. There were 616,154 Winners in this draw! Find out if you have won POWERBALL FIRST MILLIONAIRE OF THE YEAR There was no jackpot winner in Monday’s Powerball drawing. Jackpots start at $20 million and increase by a minimum of $2 million based on current game sales and interest rates. You don’t have to hit all six numbers to be a winner. Here’s a look at the different combinations you can have to win something on your Powerball ticket.  What to know about Florida Lottery:Ultimate guide to the Florida Lottery, Powerball and Mega Millions
    https://wiki-stock.win/index.php?title=Fc_twente_fixtures
    Coaching Game Changers is committed to providing you with the best possible customer service experience. Coaching Game Changers is bound by the Privacy Act 1988 (Cth), which sets out a number of principles concerning the privacy of individuals. It was only a matter of time before the generation that grew up playing Madden and games like it transformed the gridiron. For years, the sophisticated play of professional teams trickled down to their college and high school counterparts. Recently, that flow has been reversed. Now the way football is played in high school and college — a style dominated by the so-called spread offense, which involves a lot of passing and relies on quick reads by the quarterback to analyze the opposing team’s defense — is bubbling up to the NFL. The sport is being taken over by something you might call Maddenball — a sophisticated, high-scoring, pass-happy, youth-driven phenomenon.

  10. All values are rounded to the nearest hundred.

  11. DavidCooth表示:

    http://slot88.company/# Banyak kasino menawarkan permainan langsung yang seru

  12. ThomasThype表示:

    Mesin slot baru selalu menarik minat: slot 88 – slot88

  13. DavidCooth表示:

    http://bonaslot.site/# Slot klasik tetap menjadi favorit banyak orang

  14. Williecrady表示:

    Pemain sering berbagi tips untuk menang https://slotdemo.auction/# Slot dengan pembayaran tinggi selalu diminati

  15. qlhsdtmec表示:

    The NCERT solutions of Class 6 Maths Chapter 1 Knowing Our Numbers like to teach the students of grade 6 about comparing the larger numbers in different ways. Students can learn how to change the value of a number by shifting the digits, changing their places. Also, the subject experts explained the introduction of big numbers like 10,000 and 1,00,000. Not only numbers of students also taught how to find out the place value as well as keeping commas for the big numbers. But ultimately, there’s not much to be said for “why” questions when it comes to words. You imply that this is an “incorrect” thing, suggesting that you have a Platonic view of words, that there is some objectively “correct” word. But words are just conventions. It is a convention that negative numbers are not whole numbers, therefore negative numbers are not whole numbers.
    https://glamorouslengths.com/author/tacisoundvas1973/
    Tutoring in maths for students aged 5 – 16 is one of the foundation programmes at the Chorlton Tuition Centre… Mary holds two Master of Arts degrees and is a former University writing consultant. Her focus is on formal and informal writing and oral English conversation. Mary accepts learners of all ages and skill levels. Her fee is $30 per hour (negotiable). To contact Mary, please call (336) 466-7449or email her at maryebrown97@gmail” It’s time to explore some of the benefits of face to face tutoring in a tuition centre… Not only have scores sky-rocketed, but she looks forward to their sessions together. Here you’ll find the largest marketplace of the best tutors. If there a million private tutors in the world, it’s likely that the majority of those local, private tutors can be found here – so, we hope that the convenience and ease will help you be the best parent you can be.

  16. ThomasThype表示:

    Mesin slot dapat dimainkan dalam berbagai bahasa: slotdemo – slot demo

  17. ThomasThype表示:

    Pemain sering mencoba berbagai jenis slot: garuda888 slot – garuda888.top

  18. Williecrady表示:

    Banyak pemain menikmati jackpot harian di slot http://bonaslot.site/# п»їKasino di Indonesia sangat populer di kalangan wisatawan

  19. Williecrady表示:

    Permainan slot bisa dimainkan dengan berbagai taruhan http://slot88.company/# Pemain harus memahami aturan masing-masing mesin

  20. DavidCooth表示:

    http://bonaslot.site/# Banyak pemain mencari mesin dengan RTP tinggi

  21. DavidCooth表示:

    http://slot88.company/# Slot menjadi daya tarik utama di kasino

  22. Williecrady表示:

    Kasino di Bali menarik banyak pengunjung http://preman69.tech/# Bermain slot bisa menjadi pengalaman sosial

  23. Aaronbus表示:

    slot demo pg gratis demo slot pg Kasino menyediakan layanan pelanggan yang baik

  24. ThomasThype表示:

    Kasino sering mengadakan turnamen slot menarik: preman69 – preman69.tech

  25. Hi, Neat post. There’s a problem with your site in internet explorer, would check this? IE still is the market leader and a big portion of people will miss your excellent writing due to this problem.

  26. Aaronbus表示:

    slot 88 slot88 Mesin slot menawarkan berbagai tema menarik

  27. Aaronbus表示:

    preman69 preman69 Slot menawarkan kesenangan yang mudah diakses

  28. Williecrady表示:

    Pemain harus menetapkan batas saat bermain http://bonaslot.site/# Kasino menyediakan layanan pelanggan yang baik

  29. JamesLok表示:

    Banyak pemain berusaha untuk mendapatkan jackpot https://bonaslot.site/# Slot dengan fitur interaktif semakin banyak tersedia

  30. DavidCooth表示:

    http://slotdemo.auction/# Slot modern memiliki grafik yang mengesankan

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

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