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

  1. Kevinwak表示:

    A long time in the making
    Curiosity landed in Gale Crater on August 6, 2012. More than 12 years later, the rover has driven over 21 miles (34 kilometers) to ascend Mount Sharp, which is within the crater. The feature’s many layers preserve millions of years of geological history on Mars, showing how it shifted from a wet to a dry environment.
    cbridge
    Perhaps one of the most valuable samples Curiosity has gathered on its mission to understand whether Mars was ever habitable was collected in May 2013.

    The rover drilled the Cumberland sample from an area within a crater called Yellowknife Bay, which resembled an ancient lake bed. The rocks from Yellowknife Bay so intrigued Curiosity’s science team that it had the rover drive in the opposite direction to collect samples from the area before heading to Mount Sharp.
    Since collecting the Cumberland sample, Curiosity has used SAM to study it in a variety of ways, revealing that Yellowknife Bay was once the site of an ancient lake where clay minerals formed in water. The mudstone created an environment that could concentrate and preserve organic molecules and trapped them inside the fine grains of the sedimentary rock.

    Freissinet helped lead a research team in 2015 that was able to identify organic molecules within the Cumberland sample.

    The instrument detected an abundance of sulfur, which can be used to preserve organic molecules; nitrates, which are essential for plant and animal health on Earth; and methane composed of a type of carbon associated with biological processes on Earth.

    “There is evidence that liquid water existed in Gale Crater for millions of years and probably much longer, which means there was enough time for life-forming chemistry to happen in these crater-lake environments on Mars,” said study coauthor Daniel Glavin, senior scientist for sample return at NASA’s Goddard Space Flight Center in Greenbelt, Maryland, in a statement.

  2. Catxun表示:

    Дипломированный психолог с опытом работы и отзывами клиентов. Круглосуточная запись на онлайн-консультацию психолога. Дипломированный психолог с опытом работы и отзывами клиентов. оценили 1598 раз

  3. Johnniebax表示:

    Curiosity rover makes ‘arguably the most exciting organic detection to date on Mars’
    bungee exchange

    The NASA Curiosity rover has detected the largest organic molecules found to date on Mars, opening a window into the red planet’s past. The newly detected compounds suggest complex organic chemistry may have occurred in the planet’s past — the kind necessary for the origin of life, according to new research.

    The organic compounds, which include decane, undecane and dodecane, came to light after the rover analyzed a pulverized 3.7 billion-year-old rock sample using its onboard mini lab called SAM, short for Sample Analysis at Mars.

    Scientists believe the long chains of molecules could be fragments of fatty acids, which are organic molecules that are chemical building blocks of life on Earth and help form cell membranes. But such compounds can also be formed without the presence of life, created when water interacts with minerals in hydrothermal vents.

    The molecules cannot currently be confirmed as evidence of past life on the red planet, but they add to the growing list of compounds that robotic explorers have discovered on Mars in recent years. A study detailing the findings was published Monday in the journal Proceedings of the National Academy of Sciences.
    The detection of the fragile molecules also encourages astrobiologists that if any biosignatures, or past signs of life, ever existed on Mars, they are likely still detectable despite the harsh solar radiation that has bombarded the planet for tens of millions of years.

    “Ancient life, if it happened on Mars, it would have released some complex and fragile molecules,” said lead study author Dr. Caroline Freissinet, research scientist at the French National Centre for Scientific Research in the Laboratory for Atmospheres, Observations, and Space in Guyancourt, France. “And because now we know that Mars can preserve these complex and fragile molecules, it means that we could detect ancient life on Mars.”

  4. BillieLet表示:

    Achat mГ©dicament en ligne fiable: Meilleure pharmacie en ligne – pharmacie en ligne livraison europe pharmafst.com

  5. Leonardmooli表示:

    Everyone is talking about Greenland. Here’s what it’s like to visit
    cow fi

    A few months ago, Greenland was quietly getting on with winter, as the territory slid deeper into the darkness that envelops the world’s northerly reaches at this time of year.

    But President Donald Trump’s musings about America taking over this island of 56,000 largely Inuit people, halfway between New York and Moscow, has seen Greenland shaken from its frozen Arctic anonymity.

    Denmark, for whom Greenland is an autonomous crown dependency, has protested it’s not for sale. Officials in Greenland, meanwhile, have sought to assert the territory’s right to independence.

    The conversation continues to intensify. A contentious March 28 visit to a US military installation by Usha Vance, the second lady, accompanied by her husband, Vice President JD Vance, was the latest in a series of events to focus attention on Trump’s ambitions for Greenland.

    The visit was originally planned as a cultural exchange, but was shortened following complaints from Greenland Prime Minister Mute B. Egede.

    Had the Vances prolonged their scheduled brief visit, they would’ve discovered a ruggedly pristine wildernesses steeped in rich Indigenous culture.

    An inhospitable icecap several miles deep covers 80% of Greenland, forcing the Inuit to dwell along the shorelines in brightly painted communities. Here, they spend brutally cold winters hunting seals on ice under the northern lights in near perpetual darkness. Although these days, they can also rely on community stores.

    The problem for travelers over the years has been getting to Greenland via time-consuming indirect flights. That’s changing. Late in 2024, the capital Nuuk opened a long-delayed international airport. From June 2025, United Airlines will be operating a twice-weekly direct service from Newark to Nuuk.

    Two further international airports are due to open by 2026 — Qaqortoq in South Greenland and more significantly in Ilulissat, the island’s only real tourism hotspot.

  6. BradleyJaire表示:

    Kamagra Commander maintenant: kamagra 100mg prix – Kamagra pharmacie en ligne

  7. BradleyJaire表示:

    pharmacie en ligne fiable: Pharmacies en ligne certifiees – pharmacie en ligne france fiable pharmafst.com

  8. Robertfap表示:

    https://kamagraprix.com/# kamagra pas cher

  9. Robertfap表示:

    http://kamagraprix.com/# Acheter Kamagra site fiable

  10. BillieLet表示:

    pharmacie en ligne pas cher: Meilleure pharmacie en ligne – pharmacie en ligne fiable pharmafst.com

  11. Шторы на заказ с индивидуальным дизайном
    сшить шторы на заказ сшить шторы на заказ . “Ткацкий”

  12. BillieLet表示:

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

  13. RodgerJat表示:

    Remote and rugged
    eigenlayer
    A more organic way to see this coast is by the multi-day coastal ferry, the long-running Sarfaq Ittuk, of the Arctic Umiaq Line. It’s less corporate than the modern cruise ships and travelers get to meet Inuit commuters. Greenland is pricey. Lettuce in a local community store might cost $10, but this coastal voyage won’t break the bank.

    The hot ticket currently for exploring Greenland’s wilder side is to head to the east coast facing Europe. It’s raw and sees far fewer tourists, with a harshly dramatic coastline of fjords where icebergs drift south. There are no roads and the scattered population of just over 3,500 people inhabit a coastline roughly the distance from New York to Denver.

    A growing number of small expedition vessels probe this remote coast for its frosted scenery and wildlife. Increasingly popular is the world’s largest fjord system of Scoresby Sound with its sharp-fanged mountains and hanging valleys choked by glaciers. Sailing north is the prosaically named North East Greenland National Park, fabulous for spotting wildlife on the tundra.

    Travelers come to see polar bears which, during the northern hemisphere’s summer, move closer to land as the sea-ice melts. There are also musk oxen, great flocks of migrating geese, Arctic foxes and walrus.
    Some of these animals are fair game for the local communities. Perhaps Greenland’s most interesting cultural visit is to a village that will take longer to learn how to pronounce than actually walk around — Ittoqqortoormiit. Five hundred miles north of its neighboring settlement, the 345 locals are frozen in for nine months of the year. Ships sail in to meet them during the brief summer melt between June and August.

    Locked in by ice, they’ve retained traditional habits.

    “My parents hunt nearly all their food,” said Mette Barselajsen, who owns Ittoqqortoormiit’s only guesthouse. “They prefer the old ways, burying it in the ground to ferment and preserve it. Just one muskox can bring 440 pounds of meat.”

  14. Therapy表示:

    Thank you for the good writeup. It in fact was a amusement account it. Look advanced to more added agreeable from you! By the way, how could we communicate?

  15. Chesterwib表示:

    Curiosity has maintained pristine pieces of the Cumberland sample in a “doggy bag” so that the team could have the rover revisit it later, even miles away from the site where it was collected. The team developed and tested innovative methods in its lab on Earth before sending messages to the rover to try experiments on the sample.
    changelly exchange
    In a quest to see whether amino acids, the building blocks of proteins, existed in the sample, the team instructed the rover to heat up the sample twice within SAM’s oven. When it measured the mass of the molecules released during heating, there weren’t any amino acids, but they found something entirely unexpected.

    An intriguing detection
    The team was surprised to detect small amounts of decane, undecane and dodecane, so it had to conduct a reverse experiment on Earth to determine whether these organic compounds were the remnants of the fatty acids undecanoic acid, dodecanoic acid and tridecanoic acid, respectively.

    The scientists mixed undecanoic acid into a clay similar to what exists on Mars and heated it up in a way that mimicked conditions within SAM’s oven. The undecanoic acid released decane, just like what Curiosity detected.

    Each fatty acid remnant detected by Curiosity was made with a long chain of 11 to 13 carbon atoms. Previous molecules detected on Mars were smaller, meaning their atomic weight was less than the molecules found in the new study, and simpler.
    “It’s notable that non-biological processes typically make shorter fatty acids, with less than 12 carbons,” said study coauthor Dr. Amy Williams, associate professor of geology at the University of Florida and assistant director of the Astraeus Space Institute, in an email. “Larger and more complex molecules are likely what are required for an origin of life, if it ever occurred on Mars.”

  16. BradleyJaire表示:

    kamagra en ligne: Kamagra Commander maintenant – kamagra gel

  17. Peterclada表示:

    kamagra oral jelly Kamagra pharmacie en ligne kamagra 100mg prix

  18. BradleyJaire表示:

    kamagra oral jelly: achat kamagra – kamagra en ligne

  19. Robertfap表示:

    http://pharmafst.com/# pharmacie en ligne france livraison internationale

  20. Robertfap表示:

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

  21. BillieLet表示:

    kamagra 100mg prix: acheter kamagra site fiable – Acheter Kamagra site fiable

  22. LarryBug表示:

    дивитися фільми онлайн 2025 HD фільми українською онлайн

  23. BillieLet表示:

    п»їpharmacie en ligne france: Meilleure pharmacie en ligne – pharmacie en ligne pharmafst.com

  24. BradleyJaire表示:

    Kamagra Oral Jelly pas cher: Kamagra Commander maintenant – Kamagra Commander maintenant

  25. Инновационные деревянные горизонтальные жалюзи
    Деревянные горизонтальные жалюзи с электроприводом Деревянные горизонтальные жалюзи с электроприводом . Prokarniz

發佈留言

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