Summary of common instances of date classes and calendar classes in Java _java

Source: Internet
Author: User
Tags time and date

Objective
when writing a background program, often need to store the current server timestamp, the use of Timestamp is also very convenient, the client and server can be based on their own needs to do their own conversion

In PHP, get the current timestamp using the time () function, format the output through the date () function, Java is relatively complex, here a brief introduction

The Calendar,date,dateformat in the Java language form a basic but very important part of the Java standard. Dates are a key part of business logic computing, and all developers should be able to calculate future dates, customize the display format for dates, and parse text data into date objects


Get UNIX Timestamp
in JDK1.0, the date class is the only class that represents time, but since the date class is not easy to internationalize, it is recommended that the Calendar class be used for time and date processing, starting with the JDK1.1 version. Here is a brief description of how to get the current timestamp with the date class

Creates a Date object using the current date and time of the system and returns a long integer, which is often called the system time in the Java Virtual Machine (JVM) host environment, in milliseconds, and therefore needs to be converted to a Unix timestamp by dividing by 1000

 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 13:28:25 CST 2013 
    } 
  } 

Format Date
PHP can use the date () function to customize the format of dates data for rendering, Java needs to invoke the SimpleDateFormat class, such as 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); 
    } 
   

Parsing text as a Date object
given a formatted time string, such as "2013-12-17 14:05:59", you need to convert it to a Date object to get a timestamp for other formatting operations, and you can continue calling 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 ()); 
      } 
    } 
  } 

Get a specific part of a date
with the date and SimpleDateFormat two classes, we've been able to get the current timestamp, date formatted output, format date string to date object functionality, and now there's a new need to get a specific part of the date, such as the current hour, The current number of days, and so on, which requires the Calendar class to be used

  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); 
    } 
   


Calculates the number of days between two dates

For example, to calculate the number of days between April 1, 2010 and March 11, 2009, you can use time and date processing for calculations.
This program is implemented in the following principles: first represents two specific points in time, where the object of the calendar is represented, and then the two points are converted to the corresponding relative time, the difference of two time points relative to the time, and then divided by 1 days of milliseconds (24 hours X60 minutes X60 seconds X1000 milliseconds) The corresponding number of days can be obtained. The complete code to implement the example is as follows:

Import java.util.*;
/**
* Calculates the number of days between two dates */public
class DateExample1 {public
static void Main (string[] args) {
// Set two date
//Date: March 11, 2009
Calendar c1 = calendar.getinstance ();
C1.set (2009, 3-1, one);
Date: April 1, 2010
Calendar c2 = calendar.getinstance ();
C2.set (4-1, 1);
Convert to relative time
long T1 = C1.gettimeinmillis ();
Long t2 = C2.gettimeinmillis ();
Calculated days
long = (T2-T1)/(* * 1000);
System.out.println (days);
}


Print a monthly calendar for the current month

The function of the example is to output the calendar for the month in which the current system time is located, for example, the current system time is March 10, 2009, and the March 2009 calendar is exported.
The principle of this program is: first of all, get the month 1th is the day of the week, and then get the number of days of the month, and finally use Process control to achieve the format of the calendar output can be. That is, if number 1th is Monday, print a unit of space, if 1th is Tuesday, print two units of space, and so on. After the Saturday date is printed, wrap the line. The complete code to implement the example is as follows:

Import java.util.*;
/**
* Output Current month's calendar
/public class dateexample2{public
static void Main (string[] args) {
//Get current time
Calendar C = calendar.getinstance ();
The date set for the representative is number 1th
c.set (calendar.date,1);
Get number 1th is the week several
int start = C.get (Calendar.day_of_week);
Gets the maximum number of days for the current month
int maxday = C.getactualmaximum (calendar.date);
Output title
System.out.println ("Sunday Monday Tuesday Wednesday Thursday Friday Saturday");
The space for the start of the output for
(int i = 1;i < start;i++) {
System.out.print ("");
}
Outputs all dates for the month for
(int i = 1;i <= maxday;i++) {
//output Date number
System.out.print ("" + i);
Output separator space
System.out.print ("");
if (I < ten) {
System.out.print (");
}
Determine if line wrap
if ((Start + i-1)% 7 = 0) {
System.out.println ();
}
}
NewLine
System.out.println ();
}

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.