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

32,575 Responses

  1. Montebeera表示:

    order medicines online india cheapest online pharmacy india online medicine shopping in india

  2. Georgewhend表示:

    Mexican Pharm International: mexican pharmacy online – MexicanPharmInter

  3. mostbet_beSl表示:

    мостбет кыргызстан скачать http://shorts.borda.ru/?1-18-0-00000397-000-0-0 .

  4. Arthurhow表示:

    https://mexicanpharminter.com/# mexican pharmacy online store
    northern pharmacy canada

  5. vavada kasyno表示:

    Kasyno online Wawada to licencjonowane kasyno przez Internet, które oferuje korzystne warunki dla graczy niezależnie od ich doświadczenia. Na odwiedzających ten portal zawsze czekają bonusy, oryginalne gry, ciekawe promocje. Wypłata wygranych działa, możesz otrzymać dodatkowy kod promocyjny, żeby debrać no-deposit. Kontynuuj rejestrację i baw się dobrze, zgarniając wielkie wygrane!

  6. gay sex表示:

    Bonus za pierwszy depozyt i 100 spinów można otrzymać wyłącznie jeden raz. Ponowna rejestracja jest zabroniona. Podczas sezonowych promocji nowi gracze są nagradzani przez opcję “Wawada kasyno bonus bez depozytu”. Promocje są naliczane po wpisaniu kodu promocyjnego do kasyna online w formularzu rejestracyjnym.

  7. Na stałych klientów czekają różnorodne wydarzenia – turnieje, loterie oraz wyścigi. Klub hazardowy Wawada casino powraca część utraconych środków. Istnieje również program lojalnościowy. Więc poniżej przedstawiamy cechy tego programu.

  8. gay sex表示:

    Współpraca jest możliwa wyłącznie dla osób pełnoletnich. Zwracamy Twoją uwagę, że wielokrotne zakładanie konta w celu otrzymania wielu bonusów powitalnych i innych ofert od kasyna, nie jest możliwe. Jeżeli klient jest już zarejestrowany, ale nie pamięta nazwy użytkownika lub hasła, dane konta można skorygować, należy jedynie napisać wiadomość do Działu Obsługi Klienta.

  9. Georgewhend表示:

    mexican drug stores online: reliable mexican pharmacies – buying from online mexican pharmacy

  10. hello!,I like your writing very much! share we communicate more about your article on AOL? I require a specialist on this area to solve my problem. Maybe that’s you! Looking forward to see you.

  11. Montebeera表示:

    Mexican Pharm Inter Mexican Pharm Inter MexicanPharmInter

  12. Fantastic goods from you, man. I’ve keep in mind your stuff prior to and you’re just too fantastic. I really like what you have bought right here, certainly like what you’re saying and the best way through which you assert it. You make it entertaining and you continue to care for to keep it wise. I can’t wait to read much more from you. This is actually a terrific web site.

  13. Williszew表示:

    https://mexicanpharminter.shop/# buying from online mexican pharmacy

  14. Arthurhow表示:

    https://interpharmonline.com/# canada pharmacy online
    canadian pharmacies compare

  15. Arthurhow表示:

    https://indiamedfast.com/# online pharmacy india
    canadianpharmacyworld

  16. okmark your weblog and check again here regularly. I am quite sure I?ll learn many new stuff right here! Best of luck for the next!

  17. JamesGag表示:

    canadianpharmacymeds com: Certified International Pharmacy Online – canadian pharmacy world

  18. Georgewhend表示:

    Mexican Pharm Inter: Mexican Pharm Inter – Mexican Pharm Inter

  19. Williszew表示:

    https://interpharmonline.shop/# canada rx pharmacy

  20. 누누티비表示:

    Hi there, just became alert to your blog through Google, and found that it’s really informative. I am going to watch out for brussels. I will appreciate if you continue this in future. Lots of people will be benefited from your writing. Cheers!

  21. Montebeera表示:

    thecanadianpharmacy InterPharmOnline.com canadian pharmacy online store

  22. mostbet_ucma表示:

    мостбет скачать андроид mostbet794.ru .

  23. I do not even understand how I finished up here, but I believed this submit was once great. I do not realize who you are but certainly you’re going to a famous blogger for those who are not already 😉 Cheers!

  24. Joshuaerult表示:

    The crypto industry is advancing. (Just don’t ask it where it’s going.)
    trust wallet
    After a dramatic start to the year, the crypto industry is settling into a new reality — one in which the White House is laying out the red carpet and promising an unprecedented level of support.

    Crypto, a roughly 15-year-old industry that’s largely operated on the fringes of finance, is at a crossroads. For years, it has blamed a hostile regulatory environment for not allowing it to unleash its supposedly revolutionary technology on Americans. Now, though, their favorite bogeyman, Gary Gensler, the Securities and Exchange Commission chief under President Joe Biden, is gone. Crypto cheerleaders have been installed throughout the government.

    The SEC has dropped several enforcement cases against crypto companies and, starting Friday, is hosting a series of public roundtables “to discuss key areas of interest in the regulation of crypto assets.”

    Under President Donald Trump, there’s virtually nothing stopping crypto companies from creating and selling their products.

    At the same time, the same White House’s chaotic trade policy is undermining financial markets’ appetite for risk, leaving bitcoin in limbo, more than 20% off from its record high in January. And while the industry is grateful for all the attention, the White House’s embrace of some of crypto’s less savory aspects, like meme coins, has given serious investors pause.

    Given the enormous potential for the $3 trillion industry in this moment, I checked in with Eswar Prasad, a Cornell University professor of international trade and the author of the 2021 book “The Future of Money,” about the forces disrupting financial technologies.

    Fundamentally, Prasad brings a pragmatist’s view of crypto that is as refreshing as it is rare in a subject area that tends to attract zealots and loudmouths. We spoke over the phone shortly after the first-of-its-kind White House crypto summit earlier this month.

    The following interview has been edited for length and clarity.

    Nightcap: We just saw a pretty wild thing happen with the crypto summit — hard to imagine a scenario like that taking place under any previous administration. What were your takeaways?

    Eswar Prasad: The crypto industry is kissing the ring, and I think it’s getting exactly what it wants from the Trump administration, which is the legitimacy provided by government oversight, coupled with what is almost certain to be quite light touch and non-inclusive regulation.

    And I think we saw many of the major players in the crypto industry essentially using the opportunity to not just thank Trump, but try to make the point, which seemed to resonate with Trump, that this industry can power, in some sense, a resurgence of a certain part of the US economy.

  25. Frankpaync表示:

    Накрутка отзывов: Этические аспекты и последствия
    В современном мире онлайн-бизнеса отзывы пользователей стали важнейшим элементом в формировании репутации компании. Они влияют на решения потенциальных клиентов и, соответственно, на доходы предприятий. Неудивительно, что некоторые компании и индивидуальные предприниматели прибегают к накрутке отзывов. Однако эта практика вызывает серьезные этические вопросы и может иметь негативные последствия.
    Накрутка отзывов
    Что такое накрутка отзывов?
    Накрутка отзывов – это процесс создания фальшивых отзывов для искусственного улучшения репутации компании или продукта. Эти отзывы могут быть положительными, чтобы повысить рейтинг, или отрицательными, чтобы понизить рейтинг конкурентов. Существуют разные способы накрутки отзывов:

    Создание фальшивых аккаунтов: Люди или боты создают множество аккаунтов на платформах отзывов и оставляют положительные комментарии.
    Купленные отзывы: Оплата реальным пользователям за публикацию положительных отзывов.
    Манипуляция реальными отзывами: Например, удаление отрицательных отзывов или искусственное выделение положительных.
    Этические последствия
    Обман потребителей: Накрутка отзывов вводит потребителей в заблуждение, заставляя их полагаться на недостоверную информацию при принятии решений о покупке.
    Недобросовестная конкуренция: Использование фальшивых отзывов для дискредитации конкурентов нарушает принципы честной конкуренции, подрывает доверие к рынку и может привести к правовым последствиям.
    Урон репутации: Когда накрутка становится явной, это может нанести серьёзный урон репутации компании. Потребители начинают воспринимать компанию как нечестную, что значительно снижает уровень доверия и лояльности.
    Правовые аспекты
    Наряду с этическими, накрутка отзывов также имеет правовые последствия. Во многих странах она рассматривается как форма мошенничества, и компании, уличенные в этой практике, могут столкнуться с штрафами и даже судебными исками. Законы, регулирующие коммерческую практику, становятся всё более строгими. Платформы отзывов также активно борются с накруткой, применяя алгоритмы, способные выявлять и блокировать фальшивые отзывы, улучшая таким образом доверие к своему контенту.

    Как избежать негативных последствий
    Честная стратегия: Компаниям следует фокусироваться на улучшении качества своих продуктов и обслуживания клиентов. Это лучший способ заслужить искренние положительные отзывы.
    Клиентская поддержка: Активная работа с реальными отзывами, даже отрицательными, способствует улучшению репутации. Ответы на замечания и жалобы демонстрируют заботу о клиентах и желание улучшаться.
    Прозрачность: Создание доверительных отношений с клиентами через прозрачные практики ведения бизнеса способствует повышению лояльности и укреплению репутации без необходимости в накрутке.
    В заключение, накрутка отзывов, хотя и может показаться эффективным способом быстрого повышения рейтинга, является неустойчивой и потенциально разрушительной практикой. Долгосрочный успех компании строится на честности, качестве и уважении к потребителям.

  26. Arthurhow表示:

    http://interpharmonline.com/# recommended canadian pharmacies
    canadian pharmacies that deliver to the us

  27. Williszew表示:

    http://interpharmonline.com/# canadian pharmacy ltd

  28. 1win_fjpt表示:

    1вин официальный сайт 1win813.ru .

發佈留言

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