Home  >  Article  >  Java  >  Java date and time manipulation methods

Java date and time manipulation methods

高洛峰
高洛峰Original
2017-01-20 16:30:101336browse

The examples in this article share the basic operation methods of java date and time for your reference. The specific contents are as follows

1. Obtain Calendar instance: Calendar c = Calendar.getInstance();
2. Definition Date/time format: SimpleDateFormat sdf =new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
3. To convert date/time into a fixed format, use the format() method of SimpleDateFormat:
String datetime = sdf.format(c.getTime());
4. To convert the string into date/time, use the parse() method of SimpleDateFormat: Date d = sdf3.parse("2016-08-08 16:43:00");
5. To increase or decrease date/time, use Calendar's add() method, such as reducing the date by 100 days: c.add(Calendar.DATE, -100);
6. To set the date/time, 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天前:" + 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天后:" + sdf4.format(c.getTime()));
  }
}

Java date and time manipulation methods

The above is the entire content of this article. I hope it will be helpful to everyone's learning. I also hope that everyone will support the PHP Chinese website.

For more articles related to Java date and time operations, please pay attention to the PHP Chinese website!

Statement:
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