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

11,286 Responses

  1. They established their company in 1992, then transformed it in 1999 and further re-invented in 2007.

  2. When I initially commented I clicked the “Notify me when new comments are added” checkbox and now each time a comment is added I get several emails with the same comment. Is there any way you can remove me from that service? Bless you!

  3. Useful info. Lucky me I discovered your web site by accident, and I’m stunned why this coincidence didn’t took place in advance! I bookmarked it.

  4. Thomasknith表示:

    Life is Good — почему произошёл технический СКАМ проекта
    порно жесток
    Компания «Life Is Good» позиционировала себя как финансово-консалтинговый проект. Она привлекала денежные активы от клиентов, формируя из них инвестиционные вклады, которые приносят пассивный доход от 20% годовых в валюте.

    Официальный сайт компании — lifeisgood.company. Ценной информации на нем очень мало. В разделе «О компании» вместо рассказа о том, чем занимается компания, — общие фразы про финансовую независимость и благополучие клиентов, а также шесть рекламных роликов с известными людьми.
    Данная компания создана в 2014 году. Зарегистрирована в государстве-офшоре Белиз, что находится в Центральной Америке. Соответственно, выданный там сертификат не имеет на территории России никакой юридической силы. Лицензия ЦБ РФ отсутствует.

    Руководитель компании — Роман Василенко, обладатель многочисленных фотошопных регалий, количеству которых позавидовал бы даже Александр Невский (уот так уот), ветеран МЛМ движения в РФ, ну практически святой человек.

    С 1990 года по 1999 год служил в Вооруженных силах РФ.

    После службы работал в инвестиционной компании Save-Invest (Si), зарегистрированной в Швейцарии, которая обещала инвестиционные продукты со сверх доходностью. В 2000х годах газета Коммерсантъ выпустила статью о расследовании сотрудников ФСБ на предмет ведения мошеннической деятельности в РФ.

    В 2012 году руководитель Оренбургского управления Татьяна Горынина, обманувшая своих клиентов на 50 млн. получила 6 лет тюрьмы за мошенничество.

    Далее работал в инвестиционной компании “Life Division”, которая до сих пор продолжает свою работу.

    Также Роман активно ведёт блог в инстаграмме и на ютуб, темы всё те же — успешный успех, освободись от рабства, нужно только захотеть и т.д.

    Участники делали ежемесячные взносы в счет стоимости будущей квартиры. Значительная часть средств шла организаторам компании, а все остальное делились между вышестоящими пайщиками.
    Наступила стадия «критического дна», т.е. взносов от новичков поступало меньше, чем необходимо выплачивать более «старым» клиентам, основатели компании приостановили свою деятельность, а суммы, которые многие годы вносили пайщики, им просто не вернули.

    Life Is Good позиционировала себя как европейская компания, но привлекала в основном Россиян. Кстати, официальный сайт Life is Good переведен сразу на 9 языков. Непонятно для чего это сделано, ведь компания работает только в России, Казахстане и Киргизии. Наверное, поэтому над переводом на английский язык здесь не стали заморачиваться. С первого взгляда видны грубые грамматические ошибки.

    Компания работала в сотрудничестве с еще тремя: Best Way, Hermes Management и Vista.

    Гарантий сохранности денег не давала ни «Лайф-из-гуд», ни «Гермес-менеджмент». Но при этом «Лайф-из-гуд» все же предлагала страхование вложенных денег по оригинальной схеме.

  5. I’m curious to find out what blog platform you have been working with? I’m having some minor security problems with my latest site and I’d like to find something more risk-free. Do you have any solutions?

  6. DouglasGed表示:

    mexican online pharmacies prescription drugs: mexico pharmacy win – mexico drug stores pharmacies

  7. DouglasGed表示:

    mexico drug stores pharmacies: mexico pharmacy win – mexico pharmacies prescription drugs

  8. DouglasGed表示:

    buy erectile dysfunction medication: Best ED pills non prescription – discount ed meds

  9. WONDERFUL Post.thanks for share..extra wait .. ?

  10. Leonardpar表示:

    https://indiapharmacy.shop/# best india pharmacy

  11. Leonardpar表示:

    http://edpillpharmacy.store/# top rated ed pills

  12. Hey there! I just wanted to ask if you ever have any problems with hackers? My last blog (wordpress) was hacked and I ended up losing many months of hard work due to no data backup. Do you have any methods to protect against hackers?

  13. Greetings! I’ve been reading your site for a while now and finally got the courage to go ahead and give you a shout out from Porter Texas! Just wanted to say keep up the great job!

  14. I do enjoy the manner in which you have framed this problem plus it does indeed supply me personally some fodder for consideration. Nevertheless, because of everything that I have experienced, I basically hope when the responses stack on that people keep on issue and in no way embark upon a soap box involving some other news of the day. Anyway, thank you for this fantastic piece and though I do not really agree with it in totality, I regard the standpoint.

  15. Thanks for the several tips provided on this weblog. I have realized that many insurance carriers offer shoppers generous discount rates if they elect to insure more and more cars together. A significant amount of households possess several automobiles these days, particularly people with more mature teenage children still dwelling at home, as well as the savings on policies might soon increase. So it pays off to look for a great deal.

  16. Hello! I know this is somewhat off topic but I was wondering which blog platform are you using for this site? I’m getting fed up of WordPress because I’ve had issues with hackers and I’m looking at alternatives for another platform. I would be great if you could point me in the direction of a good platform.

  17. Trefojr表示:

    Привет!
    Как официально приобрести аттестат 11 класса с минимальными затратами времени
    silverdews.ru/forum/index.php
    Рады оказать помощь!.

  18. As I web site possessor I believe the content matter here is rattling fantastic , appreciate it for your efforts. You should keep it up forever! Good Luck.

  19. Today, with the fast chosen lifestyle that everyone is having, credit cards have a big demand throughout the economy. Persons from every discipline are using the credit card and people who not using the credit cards have made up their minds to apply for one. Thanks for expressing your ideas in credit cards.

  20. What i do not realize is actually how you are not actually much more well-liked than you may be now. You’re very intelligent. You realize therefore considerably relating to this subject, made me personally consider it from a lot of varied angles. Its like women and men aren’t fascinated unless it?s one thing to do with Lady gaga! Your own stuffs great. Always maintain it up!

  21. Leonardpar表示:

    https://indiapharmacy.shop/# cheapest online pharmacy india

  22. This article is a refreshing change! The author’s unique perspective and insightful analysis have made this a truly captivating read. I’m thankful for the effort he has put into crafting such an educational and thought-provoking piece. Thank you, author, for sharing your expertise and sparking meaningful discussions through your outstanding writing!

  23. It is indeed my belief that mesothelioma is actually the most dangerous cancer. It’s got unusual properties. The more I look at it a lot more I am certain it does not behave like a true solid flesh cancer. In case mesothelioma is actually a rogue viral infection, therefore there is the possibility of developing a vaccine as well as offering vaccination to asbestos open people who are open to high risk with developing future asbestos associated malignancies. Thanks for giving your ideas about this important ailment.

  24. Lazrdfk表示:

    Добрый день!
    Мы изготавливаем дипломы любых профессий по выгодным тарифам.
    telegra.ph/obuchenie-v-kanade-vuzy-08-02

  25. I also believe that mesothelioma cancer is a scarce form of melanoma that is normally found in those previously familiar with asbestos. Cancerous tissues form within the mesothelium, which is a protecting lining which covers almost all of the body’s internal organs. These cells usually form inside lining of your lungs, abdominal area, or the sac that really encircles the heart. Thanks for giving your ideas.

  26. DouglasGed表示:

    get ed prescription online: cheap ed pills online – get ed meds online

  27. of course like your website but you need to check the spelling on quite a few of your posts. A number of them are rife with spelling issues and I find it very troublesome to tell the truth nevertheless I?ll surely come back again.

  28. DouglasGed表示:

    п»їbest mexican online pharmacies: mexican pharmacy – reputable mexican pharmacies online

  29. DouglasGed表示:

    ed med online: Best ED meds online – where to buy ed pills

發佈留言

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