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

15,786 Responses

  1. Thank you, I’ve just been searching for info about this subject for ages and yours is the greatest I’ve discovered till now. But, what about the bottom line? Are you sure about the source?

  2. excellent publish, very informative. I wonder why the opposite experts of this sector do not realize this. You must continue your writing. I’m confident, you’ve a great readers’ base already!

  3. Trefnhk表示:

    Привет, друзья!
    Пошаговая инструкция по безопасной покупке диплома о высшем образовании
    napolivlz.ru/novogodnie-prazdniki-s-napoli/#comment-274327
    Рады оказать помощь!.

  4. Recently, options trading for dummies are a major topic for discussion all around.

  5. Hello there, You’ve done an excellent job. I will definitely digg it and personally suggest to my friends. I am sure they will be benefited from this website.

  6. I have observed that over the course of creating a relationship with real estate entrepreneurs, you’ll be able to come to understand that, in most real estate deal, a fee is paid. Finally, FSBO sellers will not “save” the commission. Rather, they fight to earn the commission by simply doing a great agent’s work. In this, they commit their money in addition to time to execute, as best they are able to, the assignments of an realtor. Those duties include disclosing the home via marketing, presenting the home to willing buyers, making a sense of buyer emergency in order to prompt an offer, making arrangement for home inspections, managing qualification checks with the bank, supervising fixes, and facilitating the closing of the deal.

  7. Wonderful blog! I found it while searching on Yahoo News. Do you have any tips on how to get listed in Yahoo News? I’ve been trying for a while but I never seem to get there! Appreciate it

  8. I do believe all of the ideas you have presented for your post. They’re very convincing and will definitely work. Still, the posts are very brief for beginners. May you please lengthen them a little from next time? Thank you for the post.

  9. Hello there, You have done an excellent job. I will definitely digg it and personally suggest to my friends. I am confident they will be benefited from this web site.

  10. I like the valuable info you provide in your articles. I?ll bookmark your weblog and check again here regularly. I am quite certain I will learn many new stuff right here! Best of luck for the next!

  11. In 2021, CFP Board’s latest Practice Analysis Study introduced a new Principal Knowledge Topic domain called the Psychology of Financial Planning.

  12. One important issue is that when you find yourself searching for a education loan you may find that you will want a co-signer. There are many scenarios where this is true because you might find that you do not use a past credit score so the loan provider will require you have someone cosign the financing for you. Good post.

  13. However, while you calculate the fee of the demat account, you ought to bear in mind the entire charges.

  14. Thurman表示:

    My page; Daycare Near Me [Thurman]

  15. As of July 2011, Farabourse has a complete market capitalization of $20 billion and a month-to-month quantity of $2 billion.

  16. Your website does not show up properly on my iphone 4 – you may wanna try and fix that

  17. Keithexeld表示:

    The ghost town that has stood empty for more than a century
    жесткий анальный секс
    There’s a large and very dignified school in Kayakoy. There are narrow streets, lined with houses, that wend and rise up both sides of a steep valley. There’s an ancient fountain in the middle of the town. And there are churches, one with million-dollar hilltop views over the blue Aegean.

    But, for most of the past 100 years, there have been no people.

    Kayakoy, in southwestern Turkey’s Mugla Province, is a true ghost town. Abandoned by its occupants and haunted by the past. It’s a monument, frozen in time – a physical reminder of darker times in Turkey.

    With hillsides dotted by countless crumbling buildings slowly being swallowed by greenery, and endless views into vanished lives, it’s also a fascinating and starkly beautiful place to visit. In summer, under clear skies and blazing suns, it’s eerie enough. Even more so in cooler seasons, wreathed in mountain or sea mists.
    Just over a century ago, Kayakoy, or Levissi as it was known, was a bustling town of at least 10,000 Greek Orthodox Christians, many of whom were craftspeople who lived peacefully alongside the region’s Muslim Turkish farmers. But in the upheaval surrounding Turkey’s emergence as an independent republic, their simple lives were torn apart.

    Tensions with neighboring Greece after the Greco-Turk war ended in 1922 led to both countries ejecting people with ties to the other. For Kayakoy, that meant a forced population exchange with Muslim Turks living in Kavala, in what is now the Greek region of Macedonia and Thrace.

    But the newly arrived Muslims were reputedly less than happy with their new home, swiftly moving on and leaving Kayakoy to fall to ruin.

  18. Идеальное средство для тренировки дома, который подарит вам идеальную форму.
    Spirit Fitness – залог успешного тренировочного процесса, который оценят даже самые требовательные спортсмены.
    Уникальные характеристики Spirit Fitness, для тренировки с комфортом и эффективностью.
    Выберите тренажеры Spirit Fitness для профессионального фитнеса, который будет радовать вас каждый день.

    Почувствуйте силу и энергию тренажеров Spirit Fitness, которые будут радовать вас многие годы.
    Spirit Fitness – это инновации в тренировках, для активного образа жизни.
    Spirit Fitness – лидер в мире фитнеса, который поможет вам достичь своих спортивных целей.
    Spirit Fitness – это забота о вашем здоровье, которые превратят ваши тренировки в удовольствие.

    Spirit Fitness – это ваш путь к здоровью, для заботы о своем теле.
    Spirit Fitness – лучший помощник в тренировке, которые подарят вам радость от физических упражнений.
    Spirit Fitness – это эффективность и стиль, который поможет вам формировать красивое тело.
    Spirit Fitness – для вашего идеального состояния, для занятий с комфортом.
    купить тренажеры для зала купить тренажеры для зала .

  19. Thanks for this article. I’d also like to say that it can possibly be hard if you are in school and simply starting out to initiate a long credit standing. There are many scholars who are just trying to live and have a long or beneficial credit history is often a difficult element to have.

  20. No more 402-cubic-inch engines were available.

  21. Many large newspapers and magazines have taken on more freelancers to save money on full-time employees.

  22. I will right away grab your rss as I can’t find your e-mail subscription link or e-newsletter service. Do you’ve any? Please let me know in order that I could subscribe. Thanks.

  23. Hey! Quick question that’s completely off topic. Do you know how to make your site mobile friendly? My blog looks weird when viewing from my apple iphone. I’m trying to find a theme or plugin that might be able to fix this problem. If you have any recommendations, please share. Appreciate it!

  24. While it never received the critical acclaim that its cousin the Countach garnered, the Lamborghini Jalpa was still one of the most breathtaking sports cars of the ’80s.

  25. I appreciate, cause I found just what I was looking for. You’ve ended my four day long hunt! God Bless you man. Have a great day. Bye

  26. Fantastic blog! Do you have any hints for aspiring writers? I’m hoping to start my own blog soon but I’m a little lost on everything. Would you advise starting with a free platform like WordPress or go for a paid option? There are so many choices out there that I’m completely overwhelmed .. Any recommendations? Thanks a lot!

  27. Please let me know if you’re looking for a writer for your site. You have some really good posts and I think I would be a good asset. If you ever want to take some of the load off, I’d love to write some material for your blog in exchange for a link back to mine. Please shoot me an email if interested. Kudos!

  28. Its like you read my mind! You appear to know a lot about this, like you wrote the book in it or something. I think that you can do with a few pics to drive the message home a bit, but other than that, this is excellent blog. An excellent read. I’ll definitely be back.

發佈留言

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