The examples in this article share with you the basic operating methods of java date and time for your reference. The specific content is as follows
1. Obtain Calendar instance: Calendar c = Calendar.getInstance();
2. Define the format of date/time: SimpleDateFormat sdf =new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
3. Convert date/time to a fixed format and use SimpleDateFormat's format() method:
String datetime = sdf.format(c.getTime());
4. Convert the string to date/time, use SimpleDateFormat's parse() method: Date d = sdf3.parse("2016-08-08 16:43:00");
5. To increase and decrease the date/time, use Calendar's add() method, such as reducing the date by 100 days: c.add(Calendar.DATE, -100);
6. For date/time setting, use Calendar's set() method, such as setting the hour to 0:
c.set(Calendar.HOUR_OF_DAY, 0);
example:
package myCalendar;import java.text.ParseException;import java.text.SimpleDateFormat;import java.util.Calendar;import java.util.Date;public class myCalendar { public static void main(String args[]) throws Exception{ Calendar c = Calendar.getInstance(); SimpleDateFormat sdf1 =new SimpleDateFormat("yyyyMMdd"); SimpleDateFormat sdf2 =new SimpleDateFormat("HHmmss"); SimpleDateFormat sdf3 =new SimpleDateFormat("yyyyMMddHHmmss"); SimpleDateFormat sdf4 =new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); String date = sdf1.format(c.getTime()); System.out.println(date); String time = sdf2.format(c.getTime()); System.out.println(time); String dt = "20160808162405"; Date d = sdf3.parse(dt); dt = sdf4.format(d); c.setTime(d); c.add(Calendar.DATE, -100); c.set(Calendar.HOUR_OF_DAY, 0); c.set(Calendar.MINUTE, 0); c.set(Calendar.SECOND, 0); System.out.println("100 days ago:" + sdf4.format(c.getTime())); c.add(Calendar.DATE, 200); c.set(Calendar.HOUR_OF_DAY, 0); c.set(Calendar.MINUTE, 0); c.set(Calendar.SECOND, 0); System.out.println("100 days later:" + sdf4.format(c.getTime())); }} The above is all the content of this article. I hope it will be helpful to everyone's learning and I hope everyone will support Wulin.com more.