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,528 Responses

  1. Scottdaurf表示:

    пин ап казино: pin up casino – пин ап зеркало

  2. Lesliefem表示:

    ван вин 1win зеркало 1win официальный сайт

  3. Warrenmof表示:

    http://pin-up.diy/# пин ап вход

  4. лечение наркозависимости стационаре vyvod-iz-zapoya-v-stacionare-samara.ru .

  5. Scottdiz表示:

    1вин: 1win официальный сайт – 1вин зеркало

  6. Scottdaurf表示:

    пин ап вход: pin up казино – пин ап вход

  7. Scottdiz表示:

    vavada казино: вавада казино – вавада казино

  8. Uazrnrf表示:

    Здравствуйте!
    Заказать диплом ВУЗа .
    telegra.ph/kupit-diplom-ob-okonchanii-muzykalnoj-shkoly-08-13-2

  9. JamesNut表示:

    Have the Charges Against Vasilenko for Fraud Been Dropped?
    Лайф-из-Гуд
    According to various sources, the criminal prosecution of Roman Vasilenko, the founder of the marketing company “Life-is-Good” and the cooperative “Best Way,” may be discontinued. Law enforcement agencies, as informed by several senators and State Duma deputies, have re-evaluated the charges against him, taking into account that several witnesses, including those critical of Vasilenko, suggest that he is unlikely to be involved in fraud. This is primarily because he did not have direct access to the payment system servers, and it was the former IT director of “Life-is-Good,” Evgeny Naboychenko, who had been previously implicated in fraudulent activities. Vasilenko may be at fault only for having recruited Naboychenko in 2014, despite negative signals regarding his behavior and tendencies to appropriate others’ property.

    Roman Viktorovich Vasilenko is a business consultant from Saint Petersburg, the creator of a network of independent entrepreneurs promoting financial products under the auspices of the company he founded, “Life-is-Good,” and the founder of the International Business Academy (IBA).

    The network under the “Life-is-Good” brand promoted financial products such as Vista accounts for passive income by the foreign investment company “Hermes,” registered in Belize, and the acquisition of apartments in installments through the “Best Way” cooperative, which allowed members to either make an initial share payment or accumulate it in the cooperative’s account without interest. Notably, these legal entities are not directly connected.

    Vasilenko was neither a top manager nor an owner of “Hermes”—he cooperated with the company to promote its products in Russia. However, Naboychenko was an employee of “Hermes” and managed its payment system in Russia. He likely took this position on Vasilenko’s recommendation, but Vasilenko was not responsible for managing the payment system for “Hermes.”

    Unlike “Hermes,” Vasilenko was the founder and chairman of the board of the “Best Way” cooperative until the spring of 2021 (later serving as head of the supervisory board for about a year). Since spring 2022, he has been an ordinary member of the cooperative and is no longer part of its governing bodies.

    Vasilenko has worked not only in Russia but also in Kazakhstan, Kyrgyzstan, Belarus, Ukraine, Cyprus, Austria, and Hungary. Cooperative housing projects have been established in many of these countries.

    Additionally, Vasilenko is known as a philanthropist who has invested millions of rubles in supporting federal business initiatives (such as the “Synergy” forum), cultural initiatives (such as the “Dobrovidenie” festival), and other charitable activities (including support for children’s medical institutions).

    The Case

    The criminal case involving the Saint Petersburg marketing company “Life-is-Good,” the foreign investment company “Hermes,” and the “Best Way” cooperative registered in Saint Petersburg and operating throughout Russia was initiated in the fall of 2021 by the Main Investigation Department of the Ministry of Internal Affairs of Russia for Saint Petersburg and the Leningrad Region. In February of this year, the case was referred to the court and is currently being heard in the Primorsky District Court of Saint Petersburg.

    Ten people are on trial, including technical staff from “Life-is-Good” and Victor Vasilenko, Roman Vasilenko’s 83-year-old father, who is a retiree.

    The criminal case, currently being considered by the Primorsky District Court, raises many questions—these concerns existed from the beginning and have intensified as the case progressed. The defendants are charged with three articles: creating a financial pyramid, fraud, and organizing a criminal community.

    The total amount of damage is 282 million rubles, which is incomparable to the more than 8 billion rubles seized in the case, including 4 billion rubles in the accounts of the “Best Way” cooperative. The investigation has recognized 221 citizens as victims in the case.

    Roman Vasilenko was also charged in the criminal case being considered by the court and was put on the wanted list, including by Interpol, as he had reportedly been living abroad for family reasons since the COVID-19 pandemic. However, according to sources, Interpol and foreign states, including neighboring countries where he has been actively working, deemed his prosecution unjustified.

    Another criminal investigation related to Vasilenko, handled by the Saint Petersburg Main Directorate of the Ministry of Internal Affairs, concerns the management team of “Life-is-Good.”

    Questionable Accusations

    The court proceedings in the Primorsky District Court have so far not been very successful for the investigation and the prosecution: the vast majority of those who have testified in court so far have made claims against “Hermes” for amounts ranging from several hundred to several tens of thousands of rubles, which raises eyebrows—this is not a small claims court to discuss such sums! Prosecution witness Roman Roganovich, an IT service employee, testified that he did not post any illegal information on the “Life-is-Good” website or the cooperative’s website and did not witness any illegal activity.

    Moreover, the overwhelming majority of “Hermes” clients, numbering over two hundred thousand in Russia, and tens of thousands of “Best Way” cooperative members, according to representatives of organizations defending these entities, consider law enforcement agencies to be the source of their problems. They emphasize that it was Evgeny Naboychenko, the Saint Petersburg system administrator hired by “Hermes,” who dismantled the Russian payment system. And if anyone is responsible for the thefts, it is Naboychenko. It seems that law enforcement authorities are beginning to understand this fact as well.

  10. Scottdiz表示:

    vavada казино: вавада зеркало – vavada

  11. Lazrnku表示:

    Здравствуйте!
    Мы можем предложить дипломы любой профессии по выгодным тарифам.
    cse.google.bi/url?sa=t&url=aurus-diploms.com

  12. Zgzqxz表示:

    purchase diclofenac generic – order aspirin pills order aspirin 75 mg for sale

  13. Darrelherse表示:

    slot bahis siteleri: bonus veren casino slot siteleri – en iyi slot siteleri 2024

  14. как начать зарабатывать в интернете как начать зарабатывать в интернете .

  15. Researchers in this area examine how genetic variations can impact behavior and personality traits, as well as how natural selection has affected the evolution of behavior.

  16. HIAS Welcome Campaign: More than 430 synagogues take part in this marketing campaign to help newly resettled refugee households in their communities.

  17. KevinSounc表示:

    http://sweetbonanza.network/# sweet bonanza slot demo

  18. Firstly, firms can customise their choices for every buyer.

  19. That is a premium of $8,145.

  20. You’ll be able to also profit from it according to the time body you end up picking.

  21. New York bankers to do the identical to shore up the banking system.

  22. There are also several ETFs that implement covered call strategies throughout the funds.

  23. The QuickSnap was a one-time-use digicam and it became an immediate hit out there.

  24. The notion of getting a yard koi pond surrounded by lush vegetation may enchantment to you — till you research the accompanying price tag.

發佈留言

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