Java中,可以使用SimpleDateFormat类来格式化日期和时间。下面是一些常用的日期时间格式的示例:
1. 格式化当前日期和时间:
`java
import java.text.SimpleDateFormat;
import java.util.Date;
public class Main {
public static void main(String[] args) {
Date currentDate = new Date();
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String formattedDate = dateFormat.format(currentDate);
System.out.println(formattedDate);
}
输出结果:2022-01-01 12:34:56
2. 自定义日期时间格式:
`java
import java.text.SimpleDateFormat;
import java.util.Date;
public class Main {
public static void main(String[] args) {
Date currentDate = new Date();
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy年MM月dd日 HH时mm分ss秒");
String formattedDate = dateFormat.format(currentDate);
System.out.println(formattedDate);
}
输出结果:2022年01月01日 12时34分56秒
3. 解析字符串为日期对象:
`java
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
public class Main {
public static void main(String[] args) {
String dateString = "2022-01-01 12:34:56";
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
try {
Date parsedDate = dateFormat.parse(dateString);
System.out.println(parsedDate);
} catch (ParseException e) {
e.printStackTrace();
}
}
输出结果:Sat Jan 01 12:34:56 GMT 2022
以上示例中,通过SimpleDateFormat类的构造函数传入指定的日期时间格式字符串,然后使用format方法将日期对象格式化为字符串,或者使用parse方法将字符串解析为日期对象。
注意:SimpleDateFormat是非线程安全的,如果在多线程环境下使用,应考虑使用ThreadLocal来保证线程安全性。还可以使用Java 8中的DateTimeFormatter类来进行日期时间格式化和解析操作。