Java time correlation processing summary

  • 2020-04-01 02:21:48
  • OfStack

Calculate the maximum number of days in a given month


Calendar time=Calendar.getInstance();
time.clear();
time.set(Calendar.YEAR,year); //Year for the int
time.set(Calendar.MONTH,i-1);//Notice that the Calendar object defaults to January 0& PI;                
int day=time.getActualMaximum(Calendar.DAY_OF_MONTH);//The number of days in this month
 Note: in use set Before the method, must first clear Otherwise, a lot of information will inherit from the system's current time 

2. Conversion of Calendar and Date

(1) Calendar is converted to Date


Calendar cal=Calendar.getInstance();
Date date=cal.getTime();

(2) Date is converted to Calendar

Date date=new Date();
Calendar cal=Calendar.getInstance();
cal.setTime(date);

3. Format the output date and time (this is used a lot)

Date date=new Date();
SimpleDateFormat df=new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
String time=df.format(date);
System.out.println(time);

Count the weeks of the year

(1) calculate the number of weeks a day is in a year


Calendar cal=Calendar.getInstance();
cal.set(Calendar.YEAR, 2006);
cal.set(Calendar.MONTH, 8);
cal.set(Calendar.DAY_OF_MONTH, 3);
int weekno=cal.get(Calendar.WEEK_OF_YEAR);

(2) calculate the number of days in the year

SimpleDateFormat df=new SimpleDateFormat("yyyy-MM-dd");
Calendar cal=Calendar.getInstance();
cal.set(Calendar.YEAR, 2006);
cal.set(Calendar.WEEK_OF_YEAR, 1);
cal.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY);
System.out.println(df.format(cal.getTime()));

Output:
2006-01-02

5. Usage of add() and roll() (not very common)

(1) the add () method


SimpleDateFormat df=new SimpleDateFormat("yyyy-MM-dd");
Calendar cal=Calendar.getInstance();
cal.set(Calendar.YEAR, 2006);
cal.set(Calendar.MONTH, 8);
cal.set(Calendar.DAY_OF_MONTH, 3);
cal.add(Calendar.DATE, -4);
Date date=cal.getTime();
System.out.println(df.format(date));
cal.add(Calendar.DATE, 4);
date=cal.getTime();
System.out.println(df.format(date));

Output:
      2006-08-30
      2006-09-03
(2) roll method

cal.set(Calendar.YEAR, 2006);
cal.set(Calendar.MONTH, 8);
cal.set(Calendar.DAY_OF_MONTH, 3);
cal.roll(Calendar.DATE, -4);
date=cal.getTime();
System.out.println(df.format(date));
cal.roll(Calendar.DATE, 4);
date=cal.getTime();
System.out.println(df.format(date));

Output:
      2006-09-29
      2006-09-03
As you can see, the roll() method is looped throughout the month, and the add() method is generally used.

6. Calculate the number of days between two arbitrary times (this is often used)
(1) pass into the Calendar object


    public int getIntervalDays(Calendar startday,Calendar endday)...{      
        if(startday.after(endday))...{
            Calendar cal=startday;
            startday=endday;
            endday=cal;
        }   
        long sl=startday.getTimeInMillis();
        long el=endday.getTimeInMillis();

        long ei=el-sl;          
        return (int)(ei/(1000*60*60*24));
    }

(2) pass in the Date object

    public int getIntervalDays(Date startday,Date endday)...{       
        if(startday.after(endday))...{
            Date cal=startday;
            startday=endday;
            endday=cal;
        }       
        long sl=startday.getTime();
        long el=endday.getTime();      
        long ei=el-sl;          
        return (int)(ei/(1000*60*60*24));
    }

(3) improve the method of accurately calculating the number of days apart

    public int getDaysBetween (Calendar d1, Calendar d2) ...{
        if (d1.after(d2)) ...{
            java.util.Calendar swap = d1;
            d1 = d2;
            d2 = swap;
        }
        int days = d2.get(Calendar.DAY_OF_YEAR) - d1.get(Calendar.DAY_OF_YEAR);
        int y2 = d2.get(Calendar.YEAR);
        if (d1.get(Calendar.YEAR) != y2) ...{
            d1 = (Calendar) d1.clone();
            do ...{
                days += d1.getActualMaximum(Calendar.DAY_OF_YEAR);//Get the actual days of the year
                d1.add(Calendar.YEAR, 1);
            } while (d1.get(Calendar.YEAR) != y2);
        }
        return days;
    }

Note: the above method can be derived to find any time, such as to find the mail received in the mailbox within three weeks (get the current system time - get the time before three weeks) with the time of receiving to match the best into long to compare
Such as: 1 year ago date (note the millisecond conversion)

   java.util.Date myDate=new java.util.Date();
   long myTime=(myDate.getTime()/1000)-60*60*24*365;
   myDate.setTime(myTime*1000);
   String mDate=formatter.format(myDate);

7. Conversion between String and Date, Long (most commonly used)

String to time type (string can be any type, as long as it is the same format as in SimpleDateFormat)
Usually when we take the time span, we substring the time --long -- comparison


java.text.SimpleDateFormat sdf = new java.text.SimpleDateFormat("M/dd/yyyy hh:mm:ss a",java.util.Locale.US);
java.util.Date d = sdf.parse("5/13/2003 10:31:37 AM");
long dvalue=d.getTime();
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String mDateTime1=formatter.format(d);

Find time by time

Ask for the date


SimpleDateFormat formatter2 = new SimpleDateFormat("yyyy-MM F E");
java.util.Date date2= formatter2.parse("2003-05 5  Friday ");
SimpleDateFormat formatter3 = new SimpleDateFormat("yyyy-MM-dd");
String mydate2=formatter3.format(date2);

What day of the week

mydate= myFormatter.parse("2001-1-1");
SimpleDateFormat formatter4 = new SimpleDateFormat("E");
String mydate3=formatter4.format(mydate);

9. Combination of Java and specific databases

In developing web applications, we need to do various conversions of date types in our programs for different database date types. If the corresponding database data is the Date type of oracle, that is, only the Date of year, month and day, you can choose to use the type of java.sql
You can use dateFormat to define the time and dateFormat by simply passing a string

The class Datetest {
*method converts a date of string type to a timestamp (java.sql.timestamp)
*@param dateString needs to be converted to a timestamp string
* @ return dataTime timestamp


public final static java.sql.Timestamp string2Time(String dateString)
throws java.text.ParseException {
DateFormat dateFormat;
dateFormat = new SimpleDateFormat("yyyy-MM-dd kk:mm:ss.SSS", Locale.ENGLISH);//Set the format
//dateFormat = new SimpleDateFormat("yyyy-MM-dd kk:mm:ss", Locale.ENGLISH);
dateFormat.setLenient(false);
java.util.Date timeDate = dateFormat.parse(dateString);//Util type
java.sql.Timestamp dateTime = new java.sql.Timestamp(timeDate.getTime());//Timestamp type, timedate. getTime() returns a long
return dateTime;
}

*method converts a Date of string type to a Date (java.sql.date)
*@param dateString needs to be converted to a string for Date
* @ return dataTime Date

public final static java.sql.Date string2Date(String dateString)
throws java.lang.Exception {
DateFormat dateFormat;
dateFormat = new SimpleDateFormat("yyyy-MM-dd", Locale.ENGLISH);
dateFormat.setLenient(false);
java.util.Date timeDate = dateFormat.parse(dateString);//Util type
java.sql.Date dateTime = new java.sql.Date(timeDate.getTime());//SQL type
return dateTime;
}

Public static void main(String[] args){
Date da = new Date();
Note: this place da.gettime () gets a long value
System. The out. Println (da) getTime ());

Convert from date date to timestamp

First method: use new Timestamp(long)
Timestamp t = new Timestamp(new Date(). GetTime ());
System. The out. Println (t);

Second method: use Timestamp(int year,int month,int date,int hour,int minute,int second,int nano)


Timestamp tt = new Timestamp(Calendar.getInstance().get(
      Calendar.YEAR) - 1900, Calendar.getInstance().get(
      Calendar.MONTH), Calendar.getInstance().get(
      Calendar.DATE), Calendar.getInstance().get(
      Calendar.HOUR), Calendar.getInstance().get(
      Calendar.MINUTE), Calendar.getInstance().get(
      Calendar.SECOND), 0);
System.out.println(tt);
try {
String sToDate = "2005-8-18";//String used to convert to java.sql.date
      String sToTimestamp = "2005-8-18 14:21:12.123";//A string used to convert to java.sql.timestamp
      Date date1 = string2Date(sToDate);
      Timestamp date2 = string2Time(sToTimestamp);
System.out.println("Date:"+date1.toString());//The results showed
System.out.println("Timestamp:"+date2.toString());//The results showed
}catch(Exception e) {
e.printStackTrace();
}
}


Related articles: