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

  1. nicgold表示:

    CLC Main Workbench is a professional software application specialized in advanced protein sequence analyses, data management, as well visual representations with the aid of heat maps, tables and scatter plotting options.
    The tool supports both microarray- and sequencing-based (RNA-Seq) expression data and includes all features embedded in CLC DNA Workbench, CLC RNA Workbench, and CLC Protein Workbench, as well as a range of gene expression options.
    User interface
    CLC Main Workbench comes with support for a powerful and comprehensive suite of features so be prepared to reserve some time getting used to working with the program https://jolomobli.com/festo-fluidsim-5-full-version-37/
    ec5d62056f nicgold

  2. elifalk表示:

    In case you need commercial use, please contact me via e-mail.

    Advertisements

    January 5, 2010

    With the recent releases for the Microsoft Office 2010 suite, it is clear that Microsoft is focusing on extending its reach into outlying and non-Office technologies. In this article we will consider how it has applied Office 2010 to our favourite programming language, Microsoft Visual Basic, release underst…

    January 3, 2010

    In the previous 2 articles, we put http://www.male-blog.com/wp-content/uploads/2022/06/kelroz.pdf
    ec5d62056f elifalk

  3. ozarqued表示:

    Screenshots:

    The source code is available:

    The author does encourage others to modify the software.
    The https://efekt-metal.pl/witaj-swiecie/
    ec5d62056f ozarqued

  4. vladnev表示:

    04702-Zhang1], [@pone.0004702-Jia1], [@pone.0004702-Arand1]–[@pone.0004702-Cadavid1]. Our findings are consistent with the role of NO in M1 cell inhibition [@pone.0004702-Timmerman1], [@pone.0004702-Cadavid1], [@pone.0004702- http://tekbaz.com/2022/06/04/jackiechanrobbhoodfullmovieinhindi-top/
    ec5d62056f vladnev

  5. dupxil表示:

    that can be prolongued from $5.00 – 30.00
    ■ No support
    ■ Denied access to some autostart keys (eg: those that start Autorun-enabled applications).
    ■ Can be several clones installed.

    Mcafee NOD32 EMET is a FREE tool that brings the same advanced engine for 64-bit antivirus protection as is present in McAfee NOD32 to EMET’s 64- https://neherbaria.org/portal/checklists/checklist.php?clid=7431
    ec5d62056f dupxil

  6. yalvojt表示:

    The classic

    7.

    Beautiful Britain Glorious Britain screensaver – is a very lovely, but not a typical screensaver.
    The windows will host a beautiful collection of British scenes, and then four smaller windows will show you the same, but this time from different angles. Then you can do a slide show. The main window will show you the progress of the slide show.
    There are various different slide show modes. It’s up to you what you like. https://www.macroalgae.org/portal/checklists/checklist.php?clid=5393
    ec5d62056f yalvojt

  7. raffmelo表示:

    + ⊄ Client: Cheat Engine 5.0-todd; Server: EasyChat 8.2 – Hotfix 0.75; Server host: ABCHOSTS – TheDevil-land;
     
    + – This tool doesn’t require additional time to learn. You’ll need to look through the tutorial a couple of times though, but after that it takes you only a few minutes to start using QuuSoft Desktop Manager.
    With the simple interface, you https://pristinemag.com/wp-content/uploads/2022/06/jakokav.pdf
    ec5d62056f raffmelo

  8. Slonmob表示:

    gi4m0

    jfpmn

    xe3l

  9. valemor表示:

    The invention relates to a method for operating and maintaining an electronic component and an electronic component operating and maintaining system.
    Electronic components, in particular semiconductors (ICs, for example Si or GaAs chips), are of high cost. In order to assure the highest possible degree of independence of these electronic components from factors of uncertainty or ageing, they have to be monitored and maintained, in particular in their initial state, continuously and in a specific way.
    The concept electronics component management system https://www.rosemarywatson.com/profile/isrocalohliavia/profile
    66cf4387b8 valemor

  10. yeriesh表示:

    There is hardly any software that can inspire a user to change their lazy habits and evolve as a responsible adult. Thus, it comes as no surprise that the organizers of the C.E.O. Conference – BofA BlackRock LifeStyle & Health Sciences Conference, have come up with a conference-wide contest for attendees to win eye wear that will automate everything from setting one’s sunrise alarm to buzzing them when it’s time to shower.
    This year, the https://www.ramsterevents.com/profile/servlesweawarnasuc/profile
    66cf4387b8 yeriesh

  11. raenven表示:

    You are welcome to get in touch with the
    authors
    and report any problems you run across with this tool.

    Tabbed MDI Form

    MSDOTAB

    MDITAB

    API

    Programmer’s Guide

    Examples

    Tabbed MDI Form –

    Tabbed MDI Form is a prototype application that runs on most any old Windows system. It supports NTFS, FAT32, and Fat-32 formatted drives, and allows https://www.makernexus.com/profile/niimaalivarosi/profile
    66cf4387b8 raenven

  12. odypenn表示:

    Just right click on the archive icon and select “Change Icon” to have a different alternative.

    Reviews of the Windows Archive Icons

    Below you can read real reviews of the icons gallery provided by our users.

    Once you have changed the archive icon you will have to re-arrange the files in your folder to make use of all the new icons in your suite.

    Added: 8/19/2008

    Last Edited: 11/5/ https://www.rakugo.lol/profile/The-Nirhua-Rikshawala-2-Movie-UPD-Download-In-Hindi/profile
    66cf4387b8 odypenn

  13. cathjan表示:

    Nevertheless, its use will become easy.// RUN: clspv %s -o %t.spv
    // RUN: spirv-dis -o %t2.spvasm %t.spv
    // RUN: FileCheck %s < %t2.spvasm
    // RUN: spirv-val –target-env vulkan1.0 %t.spv

    // CHECK: %[[glsl https://www.waspsnetball.co.uk/profile/glasgartokurztila/profile
    66cf4387b8 cathjan

  14. keylcele表示:

    What is new in this release:

    Fixed a bug that caused the app not to work.

    What is new in version 6.3.1:

    Improved the icon.

    Other XML files:

    – AlternativeNames.xml

    – AboutFixWinXP.xml

    – FixWinXP_etc.xml

    What is new in version 5.1:

    Fixed a bug when using FixWinXP.exe from a command line https://www.jemotorworks.co.uk/profile/icvatagisiterc/profile
    99d5d0dfd0 keylcele

  15. Slonmob表示:

    cp8ye

    o1f72

    dz94

  16. orxoyqpm表示:

    side effects of erythromycin erythromycin and acne

  17. RobertRhync表示:

    pay cialis with pay pal generic cialis canada do you need a prescription for cialis

  18. RobertRhync表示:

    cialis tadalafil & dapoxetine cialis pills cialis kidney function

發佈留言

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