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

20,489 Responses

  1. HP accused Autonomy of deliberately inflating the value of the company prior to its takeover, which the previous administration group of Autonomy denied.

  2. 3) Regulations 2020 (SI 558) come into impact, again without prior parliamentary scrutiny.

  3. Allotment gardening was extensively standard in the previous Czechoslovakia underneath the communist regime.

  4. At its inception, RACER’s portfolio included properties at 89 areas in 14 states, comprising 358 individual parcels and more than 7,000 acres of primarily industrial land, making RACER one of the most important holders of industrial property within the United States.

  5. A typical program might include a best practices approach, establishing the engagement, data gathering, clarifying financial status, financial management, risk management, tax planning, education planning, retirement planning, estate planning, asset management, planning for the closely held business, developing and presenting the financial plan, implementation and monitoring, modular planning and special planning goals, and regulatory, ethical, and legal issues, as well as marketing and practice management.

  6. Julissa表示:

    Feel free to surf to my blog Explore Daycares Locations (Julissa)

  7. Since the 2005/06 season, Helvetia has been an association sponsor of Swiss-Ski, the Swiss ski association and umbrella organisation of Swiss snow sports activities.

  8. Simple, graceful bowls of, say, art glass or metal appear to float.

  9. Dependent relations are covered by the contributions paid by employed members of the family.

  10. Lewin, Tamar (10 December 2008).

  11. If you are caught for drunk driving, certainly your driving license can be revoked and suspended thus taking you away from driving again for long period of time.

  12. On June 7, a moderate threat was issued for elements of Southern Wisconsin, Northwestern Illinois and Iowa.

  13. The price of oil rose to $77 per barrel on 24 June 2010 as a cyclone begins to form in the south western Caribbean.

  14. 下天とは表示:

    NWS Injury Survey for 01/16/22 Victoria Falls/Lely Resort (Report).

  15. ​This  data h as been done  by G SA Conte nt​ G​enerator DEMO !

  16. As a comparison, the straight corporate bond market would be about 14,000 bn USD.

  17. povo 保険表示:

    Anyanwu, Obi (September 11, 2019).

  18. Darrelherse表示:

    oyun siteleri slot: slot casino siteleri – slot casino siteleri

  19. Antonethuth表示:

    End of an era: The big change coming to European travel in November
    вебка модель работа

    In travel news this week: an accidental megadeal on first-class tickets, the world’s best-connected airport and why now is a good time to plan a trip to Europe. Plus a bit of relief for those of you traveling this Labor Day weekend.

    Goodbye to EU passport stamps
    Paper mementoes of our travels, from boarding cards to even passports themselves, are fast moving into obsolescence.

    The inky, smudgy joy of a fresh passport stamp will be a thing of the past for visitors to the 29 countries of the European Union Schengen Area starting November 10. That’s when the new automated Entry/Exit System (EES) comes into effect.

    It’s separate from the delayed ETIAS visa waiver program, which is due to start in the first half of 2025 and will mean travelers from outside the EU will be charged a €7 entry fee that is valid for three years.

    Destination inspiration
    Get your stamps while you can with these European vacation picks.

    Il dolce far niente – “the sweetness of doing nothing” – has been perfected by Italians on their vacations in southern sweet spots such as Naples, Ischia, Puglia, the Amalfi Coast and Capri. These remarkable photographs by UK photographer Lucy Laucht show how to relax the Italian way.

    In Hungary, the Gresham Palace is the grandest Budapest hotel of them all, having sat in its prime position overlooking the River Danube for more than a century. Here’s how this architectural gem looks in its current incarnation.

    Finally, if you’re considering a longer stay, an idyllic Swedish town is selling off land with prices so low you might think they’re mistakes. But Gotene, 320 kilometers (200 miles) southwest of Stockholm, is indeed selling plots with prices starting at just 1 krona, or 9 US cents, per square meter (11 square feet).

    Aviation news
    An airline accidentally offered a megadeal on first-class tickets, with 300 lucky customers getting savings of 85% off. Here’s what happened next.

    The staff at Australian flag carrier Qantas must have been flat-out like a lizard drinking sorting that mess out. And if you don’t understand that lingo, it’s time to check out our guide to Aussie slang.

    An airport on the edge of southeast Europe has been named the best connected in the world, with more than 300 direct flights to unique destinations. It’s been networking fast, too; it only opened in 2018.

  20. JasonHes表示:

    This city is developing the world’s tallest timber tower, again
    работа для девушек сургут
    The US city of Milwaukee is already home to the world’s tallest timber tower. But another, even taller, wooden skyscraper could be added to its skyline, designed by Vancouver-based studio Michael Green Architects (MGA).

    The firm recently released plans for the development, which includes a 55-story tower made principally from mass timber — thick, compressed, multilayered panels of solid wood. If built, it would usurp the current world title holder, the 25-story Ascent tower by Korb + Associates Architects, as well as becoming the tallest building in the state of Wisconsin.

    MGA, which specializes in wooden architecture, hopes that the project will set a “new global benchmark for mass timber construction.”

    The project is part of the redevelopment of the Marcus Performing Arts Center, which opened in 1969 and won the Honor Award for Excellence in Architectural Design from the American Institute of Architects in 1970. Led by Neutral, which bills itself as a “regenerative development company,” the redesign will transform what is currently the center’s concrete parking lot into a space with residential units, offices, restaurants, cafes, grocery stores and public plazas. According to MGA, construction will cost an estimated $700 million. The plan is currently going through the city’s approval process, during which it is expected to evolve.

    Why timber?
    While the use of mass timber is steadily increasing worldwide, thanks to changes in building regulations and shifting attitudes towards the material, it has yet to match the sheer height of buildings made of concrete and steel — although a slew of timber high-rises have been proposed in recent years. MGA says its tower design would be approximately 600 feet (182 meters) tall — more than double the 284 feet (87 meter) tall Ascent tower.

    “The race for height is important,” said Michael Green, an architect and founder of MGA. “It’s not about showing off, it’s about showing what’s possible to the public.”

    He argued that the reason timber skyscrapers haven’t yet become mainstream is because climate change hasn’t been at the center of the conversation. “We didn’t really need to challenge the status quo of steel and concrete,” he said. “But because those materials are so hard on the climate, we had to find a different way to build towers and big buildings in general.”

  21. Hello! I know this is kinda off topic however , I’d figured I’d ask.
    Would you be interested in exchanging links or maybe guest authoring a
    blog post or vice-versa? My site addresses a lot of the same topics as yours and I feel
    we could greatly benefit from each other. If you might be interested feel free to send me an e-mail.
    I look forward to hearing from you! Wonderful
    blog by the way!

  22. 3) For people with big loans and mortgages, the asset preservation approach of calculating insurance cover is best.

  23. From this perspective, helicopter money is really an insurance policy against the failure of fiscal policy for political, legal or institutional reasons.

  24. KevinSounc表示:

    https://sweetbonanza.network/# sweet bonanza yasal site

  25. For example, a company that makes TV sets and wants to decide about the connection between the types of its products chosen by consumers and the income group of the customers.

  26. KevinSounc表示:

    https://slotsiteleri.bid/# en iyi slot siteler

  27. Donating isn’t the only way to support a team financially; you can also buy season tickets.

  28. Darrelherse表示:

    en cok kazandiran slot siteleri: yasal slot siteleri – yasal slot siteleri

發佈留言

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