Home > 类库下载 > java类库 > Java date conversion

Java date conversion

高洛峰
Release: 2016-11-03 13:58:46
Original
1694 people have browsed it

Core classes involved: Date class, SimpleDateFormat class, Calendar class

1. Date type and long type

Date type is converted to long type

Date date = new Date();//Get the current time Date type

long date2long = date.getTime();//Convert Date to long

long type to Date type

long cur = System.currentTimeMills();//Get the current time long type and return

Date long2date = new Date(cur ; mm:ss.SSS");//Set the target conversion format to yyyy-MM-dd HH:mm:ss.SSS

String date2string = sdf.format(date);//Date to String

String type to Date type

String str="2001-11-03 11:12:33.828";//Set the initial string type date

Date str2date=sdf.parse(str);//Convert String to Date

3. Date type Convert Calendar type

Date type to Calendar type

Calendar cal = Calendar.getInstance(); //Get the current time Calendar type

cal.setTime(date); //Date to Calendar

Calendar type to Date Type

Calendar cal = Calendar.getInstance();//Get the current time Calendar type

Date cal2date = cal.getTime();//Convert Calendar to Date

4. Interview questions

Q: Write a method, parameters It is a Date date, push the date back 3 days, and return the string type in the format of "yyyy-mm-dd"

public String add3Day(Date date) throws ParseException{

SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM- dd");

Calendar cal = Calendar.getInstance();

cal.setTime(date);//Convert Date to Calendar

cal.add(Calendar.DATE, 3);//Push the date back 3 days, If the days decrease by 3, it will be -3. If the month increases, Calendar.MONTH

String after = sdf.format(cal.getTime());//Calendar is converted to Date, and then converted to String

return after;

}


5. Summary

Conversion between String and basic types relies on the String.valueOf() method

Conversion between Date and String classes relies on the SimpleDateFormat class

Conversion between Date and long relies on the construct provided by Date and getTime( ) method

Date and Calendar conversion relies on the setTime() and getTime() methods provided by Calendar

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template