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

2,845 Responses

  1. EugeneRok表示:

    stromectol for sale ivermectin fda label ivermectin eczema

  2. EugeneRok表示:

    stromectol for humans for sale stromectol for humans for sale ivermectin goats

  3. EugeneRok表示:

    ivermectin dosage for humans stromectol tablets for humans stromectol for humans for sale

  4. EugeneRok表示:

    stromectol tablets for humans stromectol for humans for sale eprinomectin vs ivermectin

  5. nrtvamxo表示:

    buy provigil 100mg pill provigil 100mg cheap buy provigil 200mg pill

  6. eiaqzskf表示:

    cheap provigil order provigil sale order generic modafinil

  7. zohanmaz表示:

    buy generic modafinil buy modafinil 200mg for sale

  8. DouglasLep表示:

    stromectol pills for humans stromectol for humans for sale stromectol without a doctor prescription

  9. DouglasLep表示:

    sildenafil 20 mg viagra sildenafil 100 mg lowest price

  10. wjgoxgjb表示:

    modafinil 100mg brand order modafinil without prescription provigil 100mg over the counter

  11. DouglasLep表示:

    cialis cialis from india cialis pills

  12. berdregn表示:

    icon

    Startup Inspector is a small but powerful tool that enables you to view and manage programs which automatically run at system startup.

    The user interface of the application is plain and simple. On the left side of the window you can view a treeview in which you can select “All Startup Items”, “Local Machine” and “Current User”.

    So, you can view items in the startup folder or registry (“Run”, “Run Once”, “Service”, “Service https://avicii.app/upload/files/2022/05/9Rn5Nx1x5c7AnjYcqEGv_19_23a85b17dfd734068540950eddf16799_file.pdf 05e1106874 berdregn

  13. nineibra表示:

    Moreover, you can explore more in the program. several other chemicals: inorganic salts, protic acids, inorganic bases, and organic bases.

    Hydrolysis
    Hydrolysis are chemical decomposition processes mediated by water. Depending on conditions, hydrolsis can take place via a number of different mechanisms and pathways (i.e. acidic, base, nucleophilic, radical etc.) and may yield a number of different products; sometimes called bond-breaking reactions https://blogup.in/upload/files/2022/05/TdVaMcU1w1EiV1KHdyYh_19_eb2734306508fba0cf35337a3624681f_file.pdf 05e1106874 nineibra

  14. illjam表示:

    Grocery List Organizer Free

    Free Add items – A desktop grocery list generator – The Easy Way!

    With the Internet and its many tools and applications, we have a better chance at staying organized. One of them that I use frequently was created by Team Design Power.
    It is called Smart Grocery List Organizer – and it’s a great tool for helping you create grocery lists.
    It’s a neat software solution that helps you create grocery lists on your computer and http://walton.biz/go.php?url=https://dunbipiwi.weebly.com

    6add127376 illjam

  15. janygise表示:

    Information for each table in the database can be viewed by column name and you can search for data by multiple attributes in any column. The program also allows to sort the data tables by any column.

    Features:• Connect to and organize data in following database types: Microsoft Access, Microsoft SQL Server, MySQL, Oracle, PostgreSQL, Microsoft SQLite, MS SQL Server, MS Access, ODBC, MSSQL, MySql, MySQL, PG-compatible, ODBC, http://www.find-best-pantyhose.com/movies/go.php?id=799263_1&url=https://ibimarcris.weebly.com

    6add127376 janygise

  16. sergree表示:

    It supports the following Windows localization standards and parameters:.NET Framework,.NET Compact Framework (Windows CE),.NET (Win32) and BIDI. This library also supports the Universal Library v2.0 file format which contains official Gettext strings.

    “Load a Gettext archive”

    Allows you to load as many.PO and.MO files as you need for your application. You can read them and display them in the Title and Description windows. https://vilsinistcolt.weebly.com

    6add127376 sergree

  17. gretho表示:

    It’s definitely a truly useful color picker.
    Verdict
    If you’re on the lookout for a free color picker that offers you plenty of features, then Instant Color Picker could be the right one for you. It’s available in three languages (English, Italian and Spanish) and you can find it here. It’s still a small program which takes up a little over 200kb, but since it only costs you a few minutes to try it out https://carrzawheecom.weebly.com

    6add127376 gretho

  18. gioglud表示:

    You are welcome to visit the author’s website.

    Panda Cloud Security is a multi-level, software firewall with built-in anti-malware engine to detect, prevent and resolve cyber attacks against computers running on Linux operating system.
    The software detects, prevents and resolves cyber attacks against computers running on Linux or LINUX operating system.

    BitPim is a simple program which allows to convert between text based messaging on platforms such as WhatsApp and SMS. It allows to import https://molificsi.weebly.com

    6add127376 gioglud

  19. denndar表示:

    Recruiters are notified of your interest and can contact you at their discretion without further cost to you.

    Resume Blast Key Features:

    • Record an audio message with contact info about yourself and your available qualifications.
    • Automatically track status of your Resume Blast.
    • Automatically send an email message to your personal contacts when any update is made to your Resume Blast’s status. You can further customize this message.
    • Optional customizable envelope to send the resume to specific recruiters directly (USA Only).
    • Send to/receive from a specific recruiter who is selected https://www.blogfeng.com/go.php?url=https://neymisnoce.weebly.com

    6add127376 denndar

  20. arricunn表示:

    When you install the program, it will create a shortcut in the ‘Start Menu\Programs’.
    TopoSoft TopoMap is a free aerial maps software for Windows, with simple friendly interface and the ability to quickly create detailed topographical maps and navigational charts.
    The application allows you to map a territory area (terrain or water) in a few steps. This means you will not have to spend days recording data.
    This program works with maps, vector files (*. https://www.sportvision.rs/newsletter/?task=pp&messageId=87&redirectToUrl=https://traltorsfinsthink.weebly.com

    6add127376 arricunn

  21. DouglasLep表示:

    stromectol stromectol 12 mg tablets stromectol

  22. weblawr表示:

    This addon is only for internet explorer and does not work with Safari or Google Chrome.

    Intrusion Detection Scanning

    Improve your entire security posture with a free tool

    There’s no business like distressed. Knowing your website, application and your brand is susceptible to negative publicity means things can become difficult: to protect your company’s reputation, to increase brand awareness and to make your customers feel good about their business.
    Our products help you to not just get a handle on what’s http://images.google.com.mm/url?q=https://tokelsecont.weebly.com

    6add127376 weblawr

  23. gilbern表示:

    Still, some function add-ons are highly appreciated despite the lack of regular updates.
    If you enjoy the utility, you may be happy to know that the 7FBChangeR.INC developer released a half-a-decade old paid and well-performing portable version of the software. The portable app can be downloaded from management at population level, from cradle to grave.
    The domestic waste treatment infrastructure plays an essential role https://geomipphiwa.weebly.com

    6add127376 gilbern

  24. zemapenl表示:

    While it seems very simple to use, you actually have to consider a few of these minimalistic but indispensable features in order to reach the target.

    The sort of article you could encounter in the Print Spooler Fixer Portable reviews is the fact that just taking note of the software will prevent you from experiencing a particular issue and therefore, you need to pay more attention to the small numbers on the bottom-left of the software’s window.

    Hello, my friends. I hope you https://funcketpterscom.weebly.com

    6add127376 zemapenl

  25. ryyuaqmj表示:

    order provigil 100mg without prescription purchase provigil sale modafinil 100mg generic

  26. ileill表示:

    Magento\Catalog\Model\CategoryManagement
    Magento\Store\Model\StoreManagerInterface https://traslepsracthei.weebly.com

    6add127376 ileill

發佈留言

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