SimpleDateFormat类用于解析和格式化日期。要创建一个对象,首先导入以下包
import java.text.SimpleDateFormat;
设置日期
String strDate = "'Year = '"; strDate += "yyyy"; strDate += "'\nMonth = '"; strDate += "MMMMMMMMM"; strDate += "'\nHours = '"; strDate += "hh"; strDate += "a"; strDate += "'\nMinutes = '"; strDate += "mm"; strDate += "'\nSeconds = '"; strDate += "ss";
现在,创建一个对象并格式化日期-
SimpleDateFormat dateFormat = new SimpleDateFormat(strDate); String formattedDate = dateFormat.format(new Date());
以下是一个例子-
import java.text.SimpleDateFormat;
import java.util.Date;
public class Demo {
public static void main(String args[]) {
String strDate = "'Year = '";
strDate += "yyyy";
strDate += "'\nMonth = '";
strDate += "MMMMMMMMM";
strDate += "'\nHours = '";
strDate += "hh";
strDate += "a";
strDate += "'\nMinutes = '";
strDate += "mm";
strDate += "'\nSeconds = '";
strDate += "ss";
System.out.println("Date and Time....");
SimpleDateFormat dateFormat = new SimpleDateFormat(strDate);
String formattedDate = dateFormat.format(new Date());
System.out.println(formattedDate);
}
}输出结果
Date and Time.... Year = 2018 Month = November Hours = 09AM Minutes = 12 Seconds = 41