In the article, the API used is SimpleDateFormat, it belongs to Java.text.SimpleDateFormat, so please remember import into
To!
Usage: SimpleDateFormat SDF = new SimpleDateFormat ("Yyyy-mm-dd HH:mm:ss");
This line is the most important, it establishes the format of the conversion, YYYY is the full ad year, MM is the month, DD is the date, as for HH:MM:SS
You don't need me to explain it again!
PS: Why some format uppercase, some format lowercase, that is afraid to avoid confusion, such as MM is the month, MM is divided; HH is 24 small
While HH is a 12-hour system.
1. String Turn date
2008-07-10 19:20:00 to turn it into a date, you can use date date = Sdf.parse ("2008-07-10 19:20:00");
2. Date Turn string
If you turn today's date into a string, you can use string str = Sdf.format (new date ());
The format of this string content is similar to the 2008-07-10 19:20:00.
With this API, we can convert the date into the string format we want, for example, to export the date to 2008.
July 10, we can write this:
SimpleDateFormat SDF = new SimpleDateFormat ("yyyy mm month DD day");
String str = sdf.format (new Date ());
STR will output in accordance with the format we have set.
Attached is a simple example of writing:
Import Java.util.Date;
Import java.text.ParseException;
Import Java.text.SimpleDateFormat;
public class Convertdemo {
/**
* Date converted to string
* @param date
* @return Str
*/
public static String datetostr (date date) {
SimpleDateFormat format = new SimpleDateFormat ("Yyyy-mm-dd HH:mm:ss");
String str = format.format (date);
return str;
}
/**
* String converted to date
* @param str
* @return Date
*/
public static Date strtodate (String str) {
SimpleDateFormat format = new SimpleDateFormat ("Yyyy-mm-dd HH:mm:ss");
Date date = null;
try {
Date = Format.parse (str);
} catch (ParseException e) {
E.printstacktrace ();
}
return date;
}
public static void Main (string[] args) {
Date date = new Date ();
System.out.println ("Date to String:" + convertdemo.datetostr (date));
System.out.println ("String to date:" + convertdemo.strtodate (convertdemo.datetostr (date));
}
}