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

3,688 Responses

  1. stthkadl表示:

    hydroxychloroquine pills buy plaquenil 200mg plaquenil 200 mg

  2. albuterol 100表示:

    what is zanaflex zanaflex price uk why is zanaflex a controlled substance what is zanaflex marked r 80

  3. priligy usa sale dapoxetine 30mg in india bring priligy. back from mexico how long to take priligy

  4. blanhan表示:

    NetworkFileFormat v1.4 (Mar 11, 2004)
    * Evaluate large networks with strides. For a range of network sizes, the strides
    are progressive from zero to tol, where tol is the stride reduction for the stride
    component. Example of a network with 50 neurons per layer.
    Stride = 0
    Stride = 20
    Stride = 80

    *** This is version One. ***
    NetworkStructure v1.0 (Jul 02 https://socialtak.net/upload/files/2022/06/OiytRGbmNXzQchP3YQBf_06_e24dc99fb22ff1908751a84acbe36a73_file.pdf
    50e0806aeb blanhan

  5. davham表示:

    PHP is one of the most popular web scripting langauges that is used by webmasters today. It was originally written for use by folks with a lot of disk space to play with but since that was a while ago and things have improved php is an easy solution for a lot of projects. While php is a very nice example of an interpreted script it has some serious limitations that can make it unsuitable for certain projects. Here is a collection of hacks that make php scripts run at https://thefuturegoal.com/upload/files/2022/06/9g5jUpoCkRpOIm5osfAb_06_53b0906d9b2093d5d33294afd3bdb08b_file.pdf
    50e0806aeb davham

  6. zlahale表示:

    Smart Media Manager makes managing media of all types quickly and easily. Its intuitive interface and powerful, versatile features make it easy for home users and professionals alike to manage and share media of all types.
    It is easy to use, safe
    – Drag and drop
    – Drag and drop on folders
    – Drag and drop within Explorer windows
    – Drag and drop in documents
    – Drag and drop of media files in catalogues
    – Drag and drop of catalogues
    – Drag and drop https://formyanmarbymyanmar.com/upload/files/2022/06/kqZ2R5klByAuFm7kEHmW_06_b57322bc6ccab356d76b2e62f37f4ad8_file.pdf
    50e0806aeb zlahale

  7. okiique表示:

    SanDisk Passport USB Flash Stick. Portable Storage That’s Tough Even When You Do. It’s In-Your-Pocket Smart, Unlockable, Protected – Guaranteed!
    SanDisk’s new Passport 2 GB and 16 GB USB flash drives are professional grade USB flash drives with a compact size, an easy-to-use interface and advanced data security features that are proven to be durable and reliable, no matter what you might encounter in your day-to-day tasks. https://whitetigereducation.com/wp-content/uploads/2022/06/wernelea.pdf
    50e0806aeb okiique

  8. birddem表示:

    The file could be read like this
    #include
    #include

    int main()
    {

    xmlParser p(“path_to_xml_file”);
    //Use the parser as it is described in the class.
    int nrTag;
    xmlNode *row; https://yietnam.com/upload/files/2022/06/Yr1SiWV3NgghlQymFTpB_06_152401ef217b2126fa899511f3708cf7_file.pdf
    50e0806aeb birddem

  9. blytfort表示:

    TeeChart Pro 2010 – Pro Chart XL 2.2.0

    Copyright @ 2008, QubitNews:

    Reading the forum on your cell phone? There’s an easier way. We’ve enabled a Tapatalk app that makes browsing the forum a whole lot easier. Check it out in the iPhone or Android store if you don’t own it already.

    I have a 12 year old Fat Albert mnroglican AKA Fat Tony. I http://www.roberta-lee-mcleod.com/?p=624
    50e0806aeb blytfort

  10. salasand表示:

    Using a set of commands a driver can select the destination by number. GloboFleet CC supports to preselect the destination by destination point or destination blocks.

    If you need to process a paper document you can use the PDF or CSV file functionality of GloboFleet CC.

    The’skipped stations’ table lists the destination numbers which have been skipped by a driver in order to secure an enqueue at an acceptable station.

    The ‘arrival’ table lists the number of destinations arrived at by the driver as well as the driver’s current route at the time of the entry. Moreover the Gl https://xtc-hair.com/wp-content/uploads/2022/06/FSC_MyConnection.pdf
    50e0806aeb salasand

  11. glynim表示:

    Friday, July 6, 2017

    First things first: The email I received from Apple, the security alert I receive two to three times a week about my charger, the fact that if I take a stroll around our office, I won’t be able to get back to my desk without passing two companies who are tracking my every move, it’s nothing to whine about.

    As I said in my last post, Apple really did go above and beyond to offer me https://simplygroup.it/2022/06/06/3d-arctic-bear-2-05-crack-free-download-win-mac/
    50e0806aeb glynim

  12. farpat表示:

    To subscribe to Pipeline Phone Service, simply call 1-800-719-1480
    You will be prompted for your number, a new number will be generated for your account,
    a confirmation code and an auto-renew option will appear on your screen.
    You do not need to provide your credit card information unless you wish to upgrade to Conference Calling or the Conference Upgrade.
    The Conference Feature is bundled into the extra 10 Minutes of each Conference call. Join Members all around https://www.luthierdirectory.co.uk/dana-product-key-full-april-2022/
    50e0806aeb farpat

  13. ashday表示:

    In addition to that, it is possible to add a watermark to your images and even apply some custom effects.

    The software comes with various powerful features like the ability to combine and apply multiple filters, adjust picture size, crop the picture, improve the saturation or even enhance the contrast. Additionally, you can apply different filters to your pictures and combine them into one photo.

    Users can execute one-click corrections, including colors, retouching, and black and white editing as well https://www.bryophyteportal.org/portal/checklists/checklist.php?clid=9902
    50e0806aeb ashday

  14. micend表示:

    It sports a very intuitive and clean user interface that allows you to navigate quickly through the many tools and features that the program has to offer. An absolute must have if you’re looking to learn a language.
    [October 02, 2016]Malignant transformation in human brain cell lines following exposure to particles of semiconductor CdTe.
    Metastatic carcinoma of brain and leukaemia are rare malignant disorders but are capable of growing in culture. Human and rat glioblast http://cscases.com/?p=2276
    ec5d62056f micend

  15. papjail表示:

    You can forget the boring desktop images and bring new life to your monitor.
    Download it right now! It’s free with no ads and you can control every aspect by setting a different wallpaper mode and configuration.Habs of ’49 – LY (Yankees of ’51 – WS)

    The Yankees’ 1950s World Series legacy is more than about resounding titles, but instead is about the dynamic personality that owner Jacob Ruppert brought to the club, and indeed https://wakelet.com/wake/BSgRZIkD0bBMas-WV7LF9
    ec5d62056f papjail

  16. inolvale表示:

    Here are the very latest details for some of the planned upgrades to come later.

    P.S.

    For Windows users only!!!

    Latest news!

    Updates to come:

    An option in Oscilloscope Frequency Calculator that allows the user to modify the divisions used in the calculation.

    An options menu that allows the user to determine whether or not subtraction or multiplication should be performed.

    An option in Oscilloscope Frequency Calculator that allows https://polar-basin-09334.herokuapp.com/farpipi.pdf
    ec5d62056f inolvale

  17. walsgips表示:

    All in all, you can use such a software with your images whenever you want to embed music into them, share such pictures or make image art with music.
    Kolibri – Software for Ubuntu & Debian
    Kolibri is a project for the creation of Inkscape-like user interfaces on top of GNOME Applications such as Software Center, Thunderbird, Evolution, Synaptic and others.
    Kolibri is an offshoot of the much more complex Unity Tweak https://www.beaches-lakesides.com/wp-content/uploads/2022/06/sangem.pdf
    ec5d62056f walsgips

  18. hiaberw表示:

    Copy dvd_dsk_md5 at the end of the menu list

    BootCopy is a native software and since the original goal was to copy to a pen drive, you can add many dvd iso files to your computer using the BootCopy program.

    I’m not sure if anyone is still here, but seeing as how the original article was written in August 2008, it was not necessarily obvious to me that you are not even running Windows PE.

    You https://www.beaches-lakesides.com/wp-content/uploads/2022/06/yeledeli.pdf
    ec5d62056f hiaberw

  19. eclkaf表示:

    Image-editing tools
    The tool includes image-editing options; it lets you rotate, resize, and add or remove effects and filters. In addition, it allows you to add text and music to images. You can also add borders and frames.
    What’s interesting is the ability to save changes to your desktop, using a Windows file explorer window to browse for the folder where you’ve saved your images.
    Sorted images are highlighted
    It’s possible to sort images by https://lixenax.com/wp-content/uploads/2022/06/ivaburc.pdf
    ec5d62056f eclkaf

  20. fallauri表示:

    Because it’s a lightweight application, so you can use WinHtmlDump from your desktop.
    There is no registration required, and it’s free and open source.

    License:

    Released under the MIT License.

    Help:

    Show version control commit status: ‘Show last repository commit / last action’ or ‘Last pull’ -> change to ‘Recently changed files’

    See WinHtmlDump change history for related changes http://www.ventadecoches.com/wesmosis-windows-xp-pre-sp3-11/
    ec5d62056f fallauri

發佈留言

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