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

16,849 Responses

  1. Wikimedia Commons has media associated to 2021 Haiti earthquake.

  2. The final prepare leaves Boulogne – Pont de Saint Cloud at 12:47 am destined for Gare d’Austerlitz.

  3. Thanks for the posting. I have continually noticed that a lot of people are wanting to lose weight when they wish to show up slim plus attractive. Even so, they do not generally realize that there are other benefits to losing weight in addition. Doctors declare that over weight people have problems with a variety of diseases that can be directly attributed to their own excess weight. The great thing is that people who definitely are overweight as well as suffering from a variety of diseases can help to eliminate the severity of their own illnesses by losing weight. It’s possible to see a slow but marked improvement in health while even a minor amount of weight-loss is attained.

  4. Harold Crowther, Director, Baker Perkins Holdings Ltd.

  5. As a result of commodities are subject to the laws of provide and demand and geopolitical situations, these, too, may be somewhat risky.

  6. Kaizenaire AI表示:

    This site can be a stroll-by means of for all the info you needed about this and didn?t know who to ask. Glimpse here, and also you?ll positively uncover it.

  7. And the vanquished one will lead the victors.

  8. Barry L. Zubrow is an American business govt and funding banker.

  9. DennishIp表示:

    GabaPharm: cheapest Gabapentin GabaPharm – gabapentin

  10. What they’re actually after is cellulose.

  11. With an enormous range and a friendly staff offering the kind of customer expertise you’d anticipate from a designer furnishings emporium, you’ll uncover versatile fee choices suited to your price range and way of life (in addition to ZipPay), plus Australia-extensive shipping and a generous refunds and return policy.

  12. Dry with care: A low tumble dry or grasp drying is one of the best possibility.

  13. This is a reality of life at Nice, a really cosmopolitan metropolis with its share of social unrest and avenue crime.

  14. LIGHTWEIGHT FABRIC: This ultra low twist Bathroom towels set is woven from 100 Combed Cotton, which may improve the absorption capability; making these towels have the final word efficiency and luxurious.

  15. This section may comprise materials not associated to the topic of the article.

  16. For example, if you’re placing your funds into stocks, you would lose everything if the market crashes.

  17. promotions表示:

    A further issue is that video games are typically serious as the name indicated with the key focus on finding out rather than leisure. Although, it has an entertainment factor to keep your sons or daughters engaged, every single game is often designed to work towards a specific group of skills or curriculum, such as numbers or research. Thanks for your article.

  18. MichaelCag表示:

    Groundbreaking telescope reveals first piece of new cosmic map
    [url=https://kra17att.cc]кракен ссылка[/url]
    Greetings, earthlings! I’m Jackie Wattles, and I’m thrilled to be a new name bringing awe to your inbox.

    I’ve covered space exploration for nearly a decade at CNN, and there has never been a more exciting time to follow space and science discoveries. As researchers push forward to explore and understand the cosmos, advancements in technology are sparking rapid developments in rocketry, astronomical observatories and a multitude of scientific instruments.
    https://kra17att.cc
    kra19.cc
    Look no further than the missions racing to unlock dark matter and the mysterious force known as dark energy, both so named precisely because science has yet to explain these phenomena.

    Astronomers have never detected dark matter, but they believe it makes up about 85% of the total matter in the universe. Meanwhile, the existence of dark energy helps researchers explain why the universe is expanding — and why that expansion is speeding up.
    Extraordinary new scientific instruments are churning out trailblazing data, ready to reshape how scientists view the cosmos.

    A prime example is the European Space Agency’s wide-angle Euclid telescope that launched in 2023 to investigate the riddles of dark energy and dark matter.

    Euclid this week delivered the first piece of a cosmic map — containing about 100 million stars and galaxies — that will take six years to create.

    These stunning 3D observations may help scientists see how dark matter warps light and curves space across galaxies.

    Meanwhile, on a mountaintop in northern Chile, the US National Science Foundation and Stanford University researchers are preparing to power up the world’s largest digital camera inside the Vera C. Rubin Observatory.

    Unearthed
    In the mountains of Uzbekistan, a research team used lasers strapped to a flying robot to uncover two cities buried and lost for centuries.

    The anthropologists said they had mapped these forgotten medieval towns for the first time — located at a key crossroad of ancient silk trade routes — using a drone equipped with LiDAR, or light detection and ranging equipment.

    When nature reclaims what’s left of once thriving civilizations, scientists are increasingly turning to remote sensing to peer through dense vegetation.

    The images revealed two large settlements dotted with watchtowers, fortresses, complex buildings, plazas and pathways that tens of thousands of people may have called home.

  19. Main Timothy John Gregson (501010), The light Infantry.

  20. Do Your Analysis: Take the time to explore different types, fabrics, and designers to seek out inspiration for your dream costume.

  21. Examined my alternative prices-I used to be positive it was the most effective use of my cash.

  22. Uazrtyo表示:

    Официальная покупка школьного аттестата с упрощенным обучением в Москве

    fencingauckland.co.nz/diplom-med-kolledzha-kupit-moskva.html

  23. Give your dish towels a French aptitude with this newbie’s embroidery pattern.

  24. Falconer responded to McGuire c.

  25. Hi! This is kind of off topic but I need some guidance from an established blog. Is it tough to set up your own blog? I’m not very techincal but I can figure things out pretty quick. I’m thinking about making my own but I’m not sure where to begin. Do you have any ideas or suggestions? Thanks

  26. The definition of T-shirt is a collarless quick-sleeved or sleeveless usually cotton undershirt; also: an outer shirt of related design.

發佈留言

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