Java Date Type conversion Summary date Timestamp calendar string

Source: Internet
Author: User
Tags date1 dateformat locale

It is convenient to use timestamp to record datetime, but sometimes it is not necessary to display the milliseconds after the decimal point, so you need to redefine the format when converting to string.

timestamp converted to string: SimpleDateFormat df = new SimpleDateFormat ("Yyyy-mm-dd HH:mm:ss");//defines the format, does not display millisecondsTimestamp now = new Timestamp (System.currenttimemillis ());//Get system Current timeString str = Df.format (now); Convert String to timestamp: SimpleDateFormat df = new SimpleDateFormat ("Yyyy-mm-dd HH:mm:ss");
String time = Df.format (new Date ());Timestamp ts =timestamp.valueof (time);conversion between Date, String, timestamp!

Conversion between Date and string the main function:
public static void Main (string[] args) {
TODO auto-generated methodstub
DateFormat format = Newsimpledateformat ("Yyyy-mm-dd");
Date Date =null;
String str =null;

String to date
str = "2009-01-06";
try {
Date = Format.parse (str); Wed Sep 00:00:00 CST2007
} catch (ParseException e) {
E.printstacktrace ();
}

Date = Java.sql.Date.valueOf (str); Only the date part is retained, and the return is JAVA.SQL.DATE2007-9-26
SYSTEM.OUT.PRINTLN (date);
Date Turn string
Date = new Date (); Wed sep26 17:14:01 CST2007
str = Format.format (date); 2007-9-26
System.out.println (str);
Format =dateformat.getdateinstance (dateformat.short);
str = Format.format (date); 07-9-26
System.out.println (str);

Format =dateformat.getdateinstance (dateformat.medium);
str = Format.format (date); 2007-9-26
System.out.println (str);
Format =dateformat.getdateinstance (dateformat.full);
str = Format.format (date); Wednesday, September 26, 2007
System.out.println (str);
}

A function to convert between timestamp and string:
public static void Main (string[] args) {
TODO auto-generated methodstub
Timestamp converted to string:
SimpleDateFormat df = new SimpleDateFormat ("Yyyy-mm-ddhh:mm:ss");//defines the format, does not display milliseconds
Timestampnow = new Timestamp (System.currenttimemillis ());//Get System Current time
String str =df.format (now);
System.out.println (str);

Convert String to timestamp:
SimpleDateFormat df1 = Newsimpledateformat ("Yyyy-mm-dd HH:mm:ss");
Date Date =new date ();
String time= Df1.format (date);
Timestamp ts= timestamp.valueof (time);
SYSTEM.OUT.PRINTLN (TS);

}

1. Calculate the maximum number of days for a January

Calendar time=calendar.getinstance ();
Time.clear ();
Time.set (calendar.year,year); Year is int
Time.set (calendar.month,i-1);///Note that Calendar object default January is 0
int Day=time.getactualmaximum (calendar.day_of_month);//number of days of the month
Note: Before using the Set method, you must clear it, otherwise many of the information will inherit from the current time of the system

Conversion of 2.Calendar and date

(1) Calendar converted to date
Calendar cal=calendar.getinstance ();
Date Date=cal.gettime ();

(2) Date converted to Calendar
Date Date=new date ();
Calendar cal=calendar.getinstance ();
Cal.settime (date);

3. Convert the string to Java.util.Date
Method One:
SimpleDateFormat sdf=new SimpleDateFormat ("Yyyy-mm-dd");
Java.util.Date dt=sdf.parse ("2005-2-19");
System.out.print (Sdf.format (DT)); The output is: 2005-2-19

Method Two:
Java.util.Date Dt=null;
DateFormat df=dateformat.getdateinstance ();
Dt=df.parse ("2005-12-19");
SYSTEM.OUT.PRINTLN (DT); The output is: Mon Dec 00:00:00 CST 2005
System.out.println (Df.format (DT)); The output is: 2005-2-19

4. Convert the string to Java.sql.Date
The string must be in the "YYYY-MM-DD" format, or the illegalargumentexception exception will be thrown
Java.sql.Date sdt=java.sql.date.valueof ("2005-9-6");
System.out.println (SDT); The output is: 2005-9-6


5. Formatted output date time (this is used more)

Date Date=new date ();
SimpleDateFormat df=new SimpleDateFormat ("Yyyy-mm-ddhh:mm:ss");
String Time=df.format (date);
System.out.println (time);

One thing to note: When the SimpleDateFormat class formats a string, it can call the format () or parse () function as needed, except that format () returns the string type, and parse () returns the Java.util.Date type

6. Calculate the week ordinal of a year

(1) Calculate a day is the first week of the 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 weeks of 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

7.add () and Roll () usage (less commonly used)

(1) 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
It can be seen that the roll () method loops within this month and generally uses the Add () method;

8. Calculate the number of days between two times in the middle of any time (this is more commonly used)
(1) Pass into calendar object
Public intgetintervaldays (Calendar startday,calendarendday) {
if (Startday.after (Endday)) {
Calendar Cal=startday;
Startday=endday;
endday=cal;
}
Long Sl=startday.gettimeinmillis ();
Long El=endday.gettimeinmillis ();

LONGEI=EL-SL;
return (int) (ei/(1000*60*60*24));
}
(2) passing in a Date object

Publicint getintervaldays (Date startday,dateendday) {
if (Startday.after (Endday)) {
Date Cal=startday;
Startday=endday;
endday=cal;
}
Long Sl=startday.gettime ();
Longel=endday.gettime ();
LONGEI=EL-SL;
return (int) (ei/(1000*60*60*24));
}
(3) Improve the method of accurately calculating the number of days apart
Public Intgetdaysbetween (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_f_year);//Get the actual day of the year
D1.add (calendar.year, 1);
} while (D1.get (calendar.year)! = y2);
}
return days;
}
Note: The above method can be derived from any time, such as to find out the mailbox received within three weeks of the mail (get the current system time-and then get three weeks ago time) with the time of the pickup to match the best fit into a long to compare
such as: 1 years ago Date (note the conversion of milliseconds)
Java.util.Date mydate=newjava.util.date ();
Longmytime= (Mydate.gettime ()/1000) -60*60*24*365;
Mydate.settime (mytime*1000);
Stringmdate=formatter.format (mydate);
Date 3 weeks ago
Calendar Cal3 =calendar.getinstance ();
Cal3.add (Cal3. Date,-21);//Fetch 3 weeks ago
String date = Formatter.format (Cal3.gettime ());

9. String and Date, Long conversions (most commonly)

The string is converted into a time type (the string can be any type, as long as it is consistent with the format in SimpleDateFormat)
Usually when we take the time span, we will substring out the specific time--long-compare

Java.text.SimpleDateFormat SDF = Newjava.text.SimpleDateFormat ("m/dd/yyyy Hh:mm:ssa", 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-ddhh:mm:ss");
String Mdatetime1=formatter.format (d);

10. Time to find time

Date of month and week
SimpleDateFormat formatter2 = new SimpleDateFormat ("yyyy-mm FE");
Java.util.Date date2= formatter2.parse ("2003-05 5 Friday");
SimpleDateFormat Formatter3 = Newsimpledateformat ("Yyyy-mm-dd");
String Mydate2=formatter3.format (DATE2);

The day of the week
Mydate= myformatter.parse ("2001-1-1");
SimpleDateFormat formatter4 = new SimpleDateFormat ("E");
String Mydate3=formatter4.format (mydate);

Java and specific database integration

In the development of Web applications, for different database date types, we need to make different conversions to the date types in our programs. If the corresponding database data is of the date type of Oracle, which is only required by the date of You can choose to use the Java.sql.Date type, if the corresponding is the datetime type of the MSSQLServer database, that is, the date of the month and time, select the Java.sql.Timestamp type
You can use DateFormat to define the format of the time date, and turn a string to

Class datetest{
*method converts a date of a string type to a Timestamp (timestamp java.sql.Timestamp)
* @param datestring need to convert to timestamp string
* @return datatime Timestamp

Public final static Java.sql.Timestamp String2time (stringdatestring)
Throws Java.text.ParseException {
DateFormat DateFormat;
DateFormat = new SimpleDateFormat ("Yyyy-mm-dd kk:mm:ss. SSS ", locale.english);//Set 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 = Newjava.sql.Timestamp (Timedate.gettime ()),//timestamp type, Timedate.gettime () returns a long type
return dateTime;
}

*method converts a date of a string type to a datetime (java.sql.Date)
* @param datestring A string that needs to be converted to date
* @return Datatime Date

Public final static Java.sql.Date String2date (stringdatestring)
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 = Newjava.sql.Date (Timedate.gettime ());//sql type
return dateTime;
}

public static void Main (string[] args) {
Date da = new Date ();
Note: This place da.gettime () Gets the value of a long type
System.out.println (Da.gettime ());

Converted from date to timestamp

First method: Use new Timestamp (long)
Timestamp t = new Timestamp (new Date (). GetTime ());
System.out.println (t);

Second method: Use Timestamp (int year,int month,int date,int hour,intminute,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";//strings used to convert to Java.sql.Date
String stotimestamp = "2005-8-1814:21:12.123";//strings used to convert to Java.sql.Timestamp
Date date1 = string2date (stodate);
Timestamp date2 = String2time (Stotimestamp);
System.out.println ("Date:" +date1.tostring ());//Results show
System.out.println ("Timestamp:" +date2.tostring ());//Results show
}catch (Exception e) {
E.printstacktrace ();
}
}
}


First, the constructor of date

1.1 Constructs a date instance that reflects the time of day
Date
Public Date ()
Constructs a Date object and initializes it to reflect the current time.

1.2 Constructing a date instance from a long integer data
Date
Public date (long date)
Constructs a Date object and initializes it based on the number of milliseconds relative to GMT January 1, 1970 00:00:00.
Parameters:
Date-the number of milliseconds relative to GMT January 1, 1970 00:00:00.

1.3 A date instance is constructed from the day of the month.
Date
public Date (int,
Int month,
int date)
public Date (int,
Int month,
int date,
int hrs,
int min)
public Date (int,
Int month,
int date,
int hrs,
int min,
int sec)
These three constructors are deprecated and are calendar.set (year + 1900, month,date) or GregorianCalendar (year + 1900, month, date) in JDK version 1.1 respectively, Calendar.set (year+ 1900, month, date, hrs, min) or GregorianCalendar (year + 1900,month, date, hrs, min), Calendar.set (year + 1900, month, date, hrs,min, sec) or GregorianCalendar (year + 1900, month, date, hrs, min,sec) instead.

Java Date Type conversion Summary date Timestamp calendar string

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.