Home > Java > javaTutorial > body text

Java date conversion

伊谢尔伦
Release: 2016-12-05 13:47:37
Original
1587 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();//Date to long

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

Date long2date = new Date(cur); //long to Date

2. Date type and String type

Date type converted to String type
Date date = new Date();

SimpleDateFormat sdf = new SimpleDateFormat(“yyyy-MM-dd HH: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 and Calendar type

Date type is converted to Calendar type
Calendar cal = Calendar.getInstance(); //Get the current time Calendar type

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

Calendar type is converted to Date type
Calendar cal = Calendar.getInstance();//Get the current time Calendar type

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

4. Summary

Conversion between String and basic types relies on String.valueOf () method
The conversion between Date and String classes relies on the SimpleDateFormat class
The conversion between Date and long relies on the construct and getTime() method provided by Date
The conversion between Date and Calendar relies on the setTime() and getTime provided by Calendar () method
5. Interview questions

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

public String add3Day(Date date) throws ParseException{
   SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
   Calendar cal = Calendar.getInstance();
   cal.setTime(date);//Date转换为Calendar
   cal.add(Calendar.DATE, 3);//将日期往后推3天,减少3天则-3. 月增加则Calendar.MONTH
   String after = sdf.format(cal.getTime());//Calendar转换为Date,再转换为String
   return after;
}
Copy after login


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