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

10,419 Responses

  1. электрокарниз недорого [url=http://www.elektrokarniz2.ru]http://www.elektrokarniz2.ru[/url] .

  2. цена электрокарниз для квартиры http://www.elektrokarniz2.ru .

  3. ArthurKib表示:

    http://pharmbig24.com/# xenical pharmacy direct

  4. шторы в рулоне [url=www.rulonnye-shtory-s-elektroprivodom.ru]www.rulonnye-shtory-s-elektroprivodom.ru[/url] .

  5. RobertMef表示:

    pharmacy website india: Online medicine home delivery – india online pharmacy

  6. VictorTax表示:

    Remember when Lady Gaga ‘bled’ onstage during her shocking performance at the 2009 VMAs?
    жесткий анальный секс

    Singing about the perils of fame, being dragged out from beneath a fallen chandelier then bleeding to death in front of a roomful of celebrities: Lady Gaga was not shy about making her debut at the MTV Video Music Awards.

    The year was 2009 — many will remember it as the year rapper Ye (formerly Kanye West) stage-crashed 19-year-old Taylor Swift and suggested her award for Best Female Video should have gone to Beyonce instead. But never one to be overshadowed, Lady Gaga, then 23, made some pop culture history of her own that night.

    Her rendition of “Paparazzi” — lamenting both unrequited love and the sinister effects of hounding tabloids — has gone down in the mists of Gaga legend; not least because a lack of high-quality footage means fans must resort to watching grainy screen-recorded versions circulated on social media.
    Over the limited number of pixels, Gaga can be seen at the start of the performance in an all-white ensemble: a bejeweled, asymmetric lace bodysuit and matching cape, thigh-high boots, a feathered Keko Hainswheeler headpiece and strings of glinting pearls. As she staggered back from her piano at the song’s crescendo, however, an audible gasp swept the room as thick blood suddenly appeared to be pouring from her abdomen.

    “I’m your biggest fan, I’ll follow you until you love me,” Gaga wailed desperately, her once-pristine outfit now daubed in scarlet. She ended the number suspended above the stage, ‘dead,’ as more blood dripped from her eyes.

    “(It) gives me chills every time I watch it,” Olivia Rodrigo told MTV in 2021. “I think Lady Gaga is the best performer of our generation.” The “Drivers License” singer appeared to take notes. At this year’s Grammy Awards, she began to ‘bleed’ from clenched fists while performing her hit “vampire,” spreading fake blood across her arms and neck as the song progressed.

  7. Josephfub表示:

    rx relief pharmacy discount cards skip’s pharmacy naltrexone arrow pharmacy my brand rx

  8. Josephfub表示:

    buying from online mexican pharmacy buying from online mexican pharmacy purple pharmacy mexico price list

  9. Josephfub表示:

    cheapest online pharmacy india top 10 pharmacies in india world pharmacy india

  10. RobertMef表示:

    purple pharmacy mexico price list: purple pharmacy mexico price list – buying prescription drugs in mexico online

  11. RobertMef表示:

    mail order pharmacy india: buy medicines online in india – mail order pharmacy india

  12. поролон мебельный в розницу porolon-mebelnyj.ru .

  13. Отличный сайт! Всем рекомендую!слив курсов.net

  14. идеи для маленького бизнеса biznes-idei11.ru .

  15. MauriceGueda表示:

    п»їlegitimate online pharmacies india: indian pharmacies safe – cheapest online pharmacy india

  16. MauriceGueda表示:

    dulcolax pharmacy: viagra mastercard online pharmacy – student store pharmacy hours

  17. MauriceGueda表示:

    Eldepryl: no prescription online pharmacy ua products percocet – clozaril pharmacy registration

  18. Eugenesmivy表示:

    Drought-hit Danube River reveals scuttled German World War II ships
    жесткое порно видео
    The wrecks of explosives-laden Nazi ships sunk in the Danube River during World War II have emerged near Serbia’s river port town of Prahovo, after a drought in July and August that saw the river’s water level drop.

    Four vessels dating from before 1950 have also come to light in Hungary’s Danube-Drava National Park near Mohacs, where the Danube’s water level stood at only 1.5 meters (4.9 feet) on Tuesday, the lingering effect of severe heat waves and persistent drought in July and August.

    The vessels revealed in Prahovo were among hundreds scuttled along the Danube by Nazi Germany’s Black Sea fleet in 1944 as they retreated from advancing Soviet forces, destroying the ships themselves. The wrecks can hamper river traffic during low water levels.
    Strewn across the riverbed, some of the ships still have turrets, command bridges, broken masts and twisted hulls, while others lie mostly submerged under sandbanks.

    Endre Sztellik, a guard at the Danube-Drava national park, said of one of the ships, “we still don’t know what this is exactly. What is visible and an unfortunate fact is that the wreck is diminishing as people are interested in it and parts of it are going missing.”
    The Danube stood at 1.17 meters (3.8 feet) in Budapest on Tuesday, which compares with an all-time record low of around 0.4 meters (1.3 feet) registered in October 2018. During floods, the Danube rises well above 6 meters (19.7 feet).

    “Eastern Europe is experiencing critical drought conditions that are affecting crops and vegetation,” the European climate service Copernicus said on its website in its latest drought report, published earlier this month.

  19. ArthurKib表示:

    https://indianpharmacy.company/# mail order pharmacy india

  20. ArthurKib表示:

    https://indianpharmacy.company/# indian pharmacy online

  21. RobertMef表示:

    indian pharmacies safe: indian pharmacy – top online pharmacy india

  22. ArthurKib表示:

    http://mexicopharmacy.cheap/# medicine in mexico pharmacies

  23. Josephfub表示:

    india online pharmacy best india pharmacy best online pharmacy india

  24. RobertMef表示:

    medication from mexico pharmacy: mexican pharmaceuticals online – buying from online mexican pharmacy

  25. RobertMef表示:

    top online pharmacy india: world pharmacy india – indian pharmacy online

  26. RobertMef表示:

    buy prescription drugs from india: indianpharmacy com – top 10 online pharmacy in india

  27. MauriceGueda表示:

    mexican pharmaceuticals online: mexican pharmaceuticals online – reputable mexican pharmacies online

發佈留言

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