Summary of common instances of the Date and Calendar classes in Java

  • 2020-04-01 04:06:41
  • OfStack

preface
When writing background programs, it is often necessary to store the time stamp of the current server, which is also very convenient to use. Both the client and the server can do their own conversion according to their own needs

In PHP, the time() function is used to get the current timestamp, and the Date() function is used to format the output

Calendar, Date, and DateFormat in the Java language form a basic but very important part of the Java standard. Dates are a critical part of business logic computation, and all developers should be able to calculate future dates, customize the format in which they are displayed, and parse textual data into date objects


Gets the UNIX timestamp
In JDK1.0, the Date class is the only one that represents time, but since the Date class is not easy to internationalize, it is recommended to use the Calendar class for time and Date processing starting from JDK1.1. Here's a quick look at how to get the current timestamp with the Date class

Create a date object and return a long integer using the current date and time of the system, which is commonly referred to as the system time of the Java virtual machine (JVM) host environment in milliseconds, so divide by 1000 to convert to a UNIX timestamp

   


 import java.util.Date; 
   
  public class TimeTest { 
    public static void main(String args[]) { 
      Date time = new Date(); 
      System.out.println(time.getTime() / 1000); // 1387258105 
      System.out.println(time.toString()); // Tue Dec 17 13:28:25 CST 2013 
    } 
  } 

Format date
PHP can use the Date() function to customize the format of Date data for rendering. In Java, we need to call the SimpleDateFormat class, for example, the current time format output:

 


  import java.text.SimpleDateFormat; 
  import java.util.Date; 
   
   
  public class TimeTest { 
    public static void main(String args[]) { 
      Date time = new Date(); 
      System.out.println(time.getTime() / 1000); // 1387260201 
   
      SimpleDateFormat sdf = new SimpleDateFormat("yyyy-mm-dd HH:mm:ss"); // 2013-03-17 14:03:21 
      String str = sdf.format(time); 
      System.out.println(str); 
    } 
  } 

Parses the text into a date object
Given a formatted time string, such as "2013-12-17 14:05:59", it needs to be converted into a Date object to facilitate the acquisition of timestamp acquisition for other formatting operations. You can continue to call the SimpleDateFormat class

   


 import java.text.ParseException; 
  import java.text.SimpleDateFormat; 
  import java.util.Date; 
   
   
  public class TimeTest { 
    public static void main(String args[]) { 
      String text = "2013-12-17 14:05:59"; 
      SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); 
       
      try { 
        Date time = sdf.parse(text); 
        System.out.println(time.getTime() / 1000); 
      } catch(ParseException e) { 
        System.out.println(e.getMessage()); 
      } 
    } 
  } 

Gets a specific part of the date
Through the Date and SimpleDateFormat two classes, we have been able to achieve the current timestamp, Date format output, format Date string to Date object function, now there is a new requirement, how to get a specific part of the Date, such as the current hour, the current days, etc., this requires the use of the Calendar class


  import java.util.Calendar; 
  import java.util.Date; 
  import java.util.GregorianCalendar; 
   
   
  public class TimeTest { 
    public static void main(String args[]) { 
      Date date = new Date(); 
      GregorianCalendar gcalendar = new GregorianCalendar(); 
      gcalendar.setTime(date); 
   
      int year = gcalendar.get(Calendar.YEAR); 
      int month = gcalendar.get(Calendar.MONTH); 
      int day = gcalendar.get(Calendar.DAY_OF_MONTH); 
   
      int hour = gcalendar.get(Calendar.HOUR_OF_DAY); 
      int minute = gcalendar.get(Calendar.MINUTE); 
      int second = gcalendar.get(Calendar.MINUTE); 
   
      System.out.println(year + "-" + month + "-" + day + " " + hour + ":" + minute + ":" 
          + second); 
    } 
  } 


Calculate the number of days between the two dates

For example, the number of days between April 1, 2010, and March 11, 2009, can be calculated using time and date processing.
The program implementation principle is: first of all, on behalf of two specific point in time, using Calendar objects to represent here, and then converted to the corresponding relative time two time points, the relative time difference for two time points, and then the number of milliseconds divided by 1 day (24 hours X60 minutes X60 X1000 milliseconds) can obtain corresponding to the number of days. The complete code to implement this example is as follows:


import java.util.*;

public class DateExample1 {
public static void main(String[] args) {
//Set two dates
//Date: March 11, 2009
Calendar c1 = Calendar.getInstance();
c1.set(2009, 3 - 1, 11);
//Date: April 1, 2010
Calendar c2 = Calendar.getInstance();
c2.set(2010, 4 - 1, 1);
//Convert to relative time
long t1 = c1.getTimeInMillis();
long t2 = c2.getTimeInMillis();
//Calculate number of days
long days = (t2 - t1)/(24 * 60 * 60 * 1000);
System.out.println(days);
}
}


Outputs the calendar for the current month

The function of this example is to output the calendar for the month in which the current system time is, for example, March 10, 2009, and the calendar for March 2009.
The principle of the program is: first get the day of the week of the first month, and then get the days of the month, and finally use the flow control to achieve the format of the calendar output. If the 1st is Monday, print one space, if the 1st is Tuesday, print two Spaces, and so on. After you have printed the date for Saturday, wrap. The complete code to implement this example is as follows:


import java.util.*;

public class DateExample2{
public static void main(String[] args){
//Get the current time
Calendar c = Calendar.getInstance();
//Set the representative's date to 1
c.set(Calendar.DATE,1);
//What day of the week is the 1st
int start = c.get(Calendar.DAY_OF_WEEK);
//Gets the maximum number of dates for the current month
int maxDay = c.getActualMaximum(Calendar.DATE);
//Output the title
System.out.println(" Sunday   Monday   Tuesday   Wednesday   Thursday   Friday   Saturday ");
//Output the starting space
for(int i = 1;i < start;i++){
System.out.print(" ");
}
//Outputs all the dates in that month
for(int i = 1;i <= maxDay;i++){
//Output date number
System.out.print(" " + i);
//Output separator space
System.out.print(" ");
if(i < 10){
System.out.print(' ');
}
//Determine whether to wrap
if((start + i - 1) % 7 == 0){
System.out.println();
}
}
//A newline
System.out.println();
}
}


Related articles: